/*8.3.1 指针基础及指针运算*/ #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); //使用指针p和q输入a,b的值 printf("Result: \n"); printf("%d, %f\n", a, b); printf("%d, %f\n", *p, *q); //通过指针p和q间接输出a,b的值 printf("The Address of a,b: %p,%p\n", &a, &b); printf("The Address of a,b: %p,%p\n", p, q); //输出p和q是值并与上行输出结果进行比较 p=&c; printf("c=%d\n ", *p); printf("The Address of c: %x, %x\n", p, &c); //输出p的值及c的地址 return 0; }
/*8.3.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("\nb=: "); 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; /*交换x,y地址上的值*/ }
/*8.3.3 字符串反转及字符串连接*/ #include<stdio.h> char *reverse(char *str); char *link(char *str1,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("\nInput string1: "); gets(str); printf("Input string2: "); gets(str1); str2=link(str,str1); printf("Link string1 and string2: "); puts(str2); return 0; } char *reverse(char *str) { char *p,*q,temp; p=str,q=str; while(*p!=‘\0‘) /*判断是否到达最后一个字符*/ p++; /*p++指到最后一个元素*/ p--; /*p--指向倒数第二个字符,‘\0‘的前一位*/ 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所指向的元素*/ q++; p++; } *p=‘\0‘; /*令结束字符为空字符*/ return str1; }
/*8.3.4 数组元素奇偶排序*/ #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是否为奇数*/ p++; //指针向后移动 while(*q%2==0) /*判断*q是否为偶数*/ q--;//指针向前移动 if(p>q) break; temp=*p; *p=*q; *q=temp; p++; q--; //指针相向移动 } }
原文:https://www.cnblogs.com/nsy-2019/p/13030317.html