C程序设计实验报告
实验项目:
1、指针基础及指针运算
2、数据交换
3、字符串反转及字符串连接
4、数组元素奇偶排列
姓名: 刘健斌 实验地点:教室514 实验时间:06.12
一、实验目的与要求
1、掌握指针的概念和定义方法
2、掌握指针的操作符和指针的运算
3、掌握指针与数组的关系
4、掌握指针与字符串的关系
5、熟悉指针作为函数的参数以及返回指针的函数
6、了解函数指针
二、实验内容
8.3.1、实验练习:
1问题的简单描述:
1)定义一个整型指针变量p,使它指向一个整型变量a,定义一个浮点型指针q,使它指向一个浮点型变量b,同时定义另外一个整型变量c并赋值初值3
2)使用指针变量,调用scanf函数分别输入a,b的值
3)通过指针间接访问并输出a、b的值
4)按十六进制方式输出p、q的值以及a、b的地址
5)将p指向c,通过p的间接访问c的值并输出
6)输出p的值及c的地址,并与上面的结果进行比较
2实验代码:
#include<stdio.h> main() { int *p,a,c=3; float *q,b; p=&a; q=&b; printf("please input the value of a,b:"); scanf("%d%f", &(*p),&(*q)); printf("result: "); printf(" %d, %f ",a,b); printf(" %d, %f ",*p,*q); printf("the address of a,b:%p,%p ",&a,&b); printf("the address of a,b:%p,%p ",p,q); p=&c; printf("c=%d ",*p); printf("theaddress of c:%x,%x ",p,&c); return 0; }
输出:
3问题分析:一开始,我是按照书上的代码打的,但是得到的是:result 18,0.0000000 。看了挺久发现了问题,scanf里面是%d%f,两个数之间应该用空格隔开,而不是逗号。
8.3.2、实验练习:
1问题的简单描述:
1)定义两个函数,分别为void swap1(int a,int b)和void swap2(int *a,int *b),用于交换a,b的值。
2)从主函数中分别出入两个整型变量a,b
3)从主函数中分别调用上述两个交换函数,并打印输出交换后a,b的结果
2实验代码:
#include<stdio.h> void swap1(int x,int y); void swap2(int *x,int *y); main() { int a,b; printf("please input a=:"); scanf("%d",&a); printf(" b=:"); scanf("%d",&b); swap1(a,b); printf(" after call swap1:a=%d b=%d ",a,b); swap2(&a,&b); printf(" after call swap2:a=%d b=%d ",a,b); return 0; } void swap1(int x,int y) { int temp; temp=x; x=y; y=temp; } void swap2(int *x,int *y) { int temp; temp=*x; *x=*y; *y=temp; }
输出:
3问题分析:无
3、实验练习:
1问题的简单描述:
1)定义两个字符指针,通过gets()函数输入两个字符串
2)定义一个函数char *reverse(char *str),通过指针移动凡是将字符串反转
3)定义一个函数char *link(char *str1,char *str2),通过指针移动方式将两个字符串连接起来
4)从值函数中分别调用上述函数,输入字符串并打印输出结果
2实验代码:
#include<stdio.h> char *reverse(char *str); char *link(char *str1,char *str2); main() { char str[30],str1[30],*str2; printf("input reversing character string:"); gets(str); str2=reverse(str); printf(" output reversed character string:"); puts(str2); printf("input string1:"); gets(str); printf(" input string2:"); gets(str1); str2=link(str,str1); puts(str2); return 0; } char *reverse(char *str) { char *p,*q,temp; p=str,q=str; while( *p!='