// pointer to a character string has not changed successfully char str1 [20 is] = "Notepad"; char str2 [20 is] = "Calc"; void Change (char * str) {// copy mechanism have the function will create a new variable str to store the main function p pass over str1 the first address printf ( "str in change:% p,% p \ the n-", str, str2); // str in change: 00403008,0040301C str = str2; // change New str address pointer variable, and it did not affect the main function of the p address the printf ( "Change:% S,% p \ n-", str, str); // Change: Calc, 0040301C } void main () { char * p str1 =; printf ( "p in main:% p,% p \ the n-", p, str1); // in main p: 00403008,00403008 change (p); // change does not change the point p in printf ( " Change After:% S, P% \ n-", P, P); // After Change: Notepad, 00,403,008 }
//一级指针字符串 改变成功,改变其指向的内容 #include <string.h> char str1[20] ="notepad"; char str2[20] ="calc"; void change(char *str){ //函数有副本机制,会新建一个变量str来存储main函数中p传过来str1的首地址 printf("str in change: %p,%p\n",str,str2); //str in change: 00403008,0040301C //根据p传过来的地址,用字符数组拷贝的方式,改变主函数中p所指向的字符串 strcpy(str,str2); //把str和p共同指向的同一片内存区域的内存修改了,导致主函数也修改了 printf("change:%s,%p\n",str,str); //change:calc,00403008 } void main(){ char *p =str1; printf("p in main: %p,%p\n",p,str1); //p in main: 00403008,00403008 change(p); // //把str和p共同指向的同一片内存区域的内存修改了,导致主函数也修改了 printf("after change: %s,%p\n",p,p); //after change: calc,00403008 }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //二级指针字符串 #include <string.h> char str1[20] ="notepad"; char str2[20] ="calc"; void change(char **str){ //函数有副本机制,会新建一个二级指针变量str来存储main函数中p传过来str1的首地址 printf("str in change: %p,%p\n",str,str2); //str in change: 00403008,0040301C *str = str2; // *str就相当于一级指针 char * 用来改变main中p指针变量自己的首地址 *str=p=str2 printf("change:%s,%p\n",*str,*str); //change:calc,0040301c } void main(){ char *p =str1; printf("p in main: %p,%p\n",p,str1); //p in main: 00403008,00403008 change(&p); //change把p的指向给改变,等价于p=str2 printf("after change: %s,%p\n",p,p); //after change: calc,0040301c }