指针在C语言中的重要性不言而喻。
有这么一个场景,main函数里调用了一个func函数,所有的变量在main函数里都初始化定义了,随即调用func函数对这些变量进行重新赋值,最后会发现一个有趣的结果。
如下代码所示: 你们猜,最后的结果会是什么?
#include#include #include int func(int a, char *s2, char c) { a=97; strcpy(s2,"hello"); c='C'; return 0; } void main(void) { int a = 98; char s1[10]; char c; c='A'; strcpy(s1,"world"); func(a,s1,c); printf("%dn%sn%cn",a,s1,c); system("pause"); }
结果是:
为什么会是这样呢?
当我们给上述代码添加几行,分别返回每个时候变量的地址,此时代码如下:
#include#include #include int func(int a, char *s2, char c) { a=97; strcpy(s2,"hello"); c='C'; printf("4.a的地址是:%pn",&a); printf("5.s2的地址是:%pn",s2); printf("6.c的地址是:%pn",&c); return 0; } void main(void) { int a = 98; char s1[10]; char c; c='A'; strcpy(s1,"world"); printf("1.a的地址是:%pn",&a); printf("2.s1的地址是:%pn",&s1); printf("3.c的地址是:%pn",&c); func(a,s1,c); printf("%dn%sn%cn",a,s1,c); system("pause"); }
此时输出是:
我这里写s1和s2只是帮助大家理解这个过程,把s2换成s1结果也是一样的。
可以看到s1和s2的地址是一样的。当字符串s1传入fanc函数时,指针s2指向的是字符串s1,strcpy(s2,“hello”)是把“hello”字符串复制到指针s2指向的位置上去。最后我们printf("%s", s1),s1就是那块地址最后存放的东西。这就是“传址”。
而a和c的值在func函数里和main函数里,只是名字相同,实质根本不是同一个变量,因为它们的地址不同!也就是所说的“传值”在结束func函数调用后,不会改变main函数中变量的值。



