C程序設計實驗報告
實驗項目
8.3.1 指針基礎及指針運算
8.3.2 數據交換
8.3.3 字符串反轉及字符串連接
8.3.4 數組元素奇偶排序
姓名:熊曉東
實驗地點:贛南醫學院宿舍
實驗時間:2020.06.06
一、實驗目的與要求
1、掌握指針的概念和定義方法。
2、掌握指針的操作符和指針的運算。
3、掌握指針與數組的關系。
4、掌握指針與字符串的關系。
5、熟悉指針作為函數的參數及返回指針的函數。
6、了解函數指針。
二、實驗內容
1、實驗練習:8.3.1 指針基礎及指針運算
1問題的簡單描述:定義整型指針變量p,使之指向整型變量a;定義浮點型指針q,使之指向浮點變量b,同時定義另外一個整型變量c並賦初值3。使用指針p,q輸入a,b表達值;通過指針p,q間接輸出a,b的值;輸出p,q的值及c的地址。
2實驗代碼:
``` #include<stdio.h> int 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:\n"); printf("%d,%f\n",*p,*q); printf("The Address of a,b:%p,%p\n",&a,&b); printf("The Address of a,b:%p,%p\n",p,q); p=&c; printf("c=%d\n",*p); printf("The Address of c:%x,%x\n",*p&c); return 0; }
3問題分析:基本沒有
2、實驗練習:8.3.2 數據交換
1問題的簡單描述:從主函數中調用swap1和swap2函數,並打印輸出交換后a、b的結果。
2實驗代碼:
··· #include<stdio.h> void swap1(int x,int y); void swap2(int *x,int *y); int main() { int a,b; printf("Please Input a=:"); scanf("%d",&a); printf("Please Input b=:"); scanf("%d",&b); swap1(a,b); printf("\nAfter Call swap1:a=%d b=%d\n",a,b); swap2(&a,&b); printf("\nAfter Call swap2:a=%d b=%d\n",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、實驗練習:8.3.3 字符串反轉及字符串連接
1問題的簡單描述:定義兩個字符指針,通過指針移動方式將字符串反轉以及將兩個字符串連接起來。
2實驗代碼:
··· #include<stdio.h> char *reverse(char *str); char *link(char *str,char *str2); int main() { char str[30],str1[30],*str2; printf("Input Reversing Character String:"); gets(str); str2=reverse(str); printf("\nOutput 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!='\0') p++; p--; while (q<p) { temp=*q; *q=*p; *p=temp; q++; p--; } return str; } char *link(char *str1,char *str2) { char *p=str1,*q=str2; while(*p!='\0') p++; while(*q!='\0') { *p=*q; q++; p++; } *p='\0'; return str1; }
3問題分析:無
4、實驗練習:8.3.4 數組元素奇偶排序
1問題的簡單描述:定義一個函數,實現數組元素奇數在左、偶數在右。
2實驗代碼:
··· #include<stdio.h> #define N 10 void arrsort(int a[],int n); int main() { int a[N],i; for(i=0;i<N;i++) scanf("%d",&a[i]); arrsort(a,N); for(i=0;i<N;i++) printf("%d ",a[i]); } void arrsort(int a[],int n) { int *p,*q,temp; p=a; q=a+n-1; while(p<q){ while(*p%2!=0) p++; while(*q%2==0) q--; if (p>q) break; temp=*p; *p=*q; *q=temp; p++; q--; }}
3問題分析:要注意指針的合理使用。
三、實驗小結
本次指針實驗對指針方面的學習進行了初步的接觸和運用,在課上有很多不懂的地方,基本要聽老師來引導,在課后還需要花更多時間來消化和鞏固知識。