c语言指针类型参数的传递方式

来源:互联网 发布:人大历史系知乎 编辑:程序博客网 时间:2024/05/21 21:34
       C语言中数组类型和函数类型的参数只能是按地址传递参数;而整数类型、字符类型、浮点类型、枚举类型、指针类型、结构类型和联合类型只能是按值传递参数,这其中指针类型的参数传递方式最容易迷惑。
       下面看一个简单的例子:
       void set(char *p){
              p=NULL;
              printf("address of p is %d/n",(signed)p);
       }
 
       void main()
       {
              char *str,a='A';
              str=&a;
              printf("before call set(),the value of str is %d,value of *str is %c",(unsigned)str,*str);
              set(str);
              printf("after call set(),the value of str is %d,value of *str is %c",(unsigned)str,*str);
       }
      
       输出结果如下:
       before call set(),the value of str is 1245048,value of *str is A
       address of p is 0
       after call set(),the value of str is 1245048,value of *str is A
       由此可见,指针变量str的值在调用前后并没改变,所以它所指向的内容也不会变。
       在理解了这一点后,再回头看林锐博士的“c/c++高质量编程”中的一道题:
       void GetMemory(char *p)
       {
              p = (char *)malloc(100);
       }
       void Test(void)
       {
              char *str = NULL;
              GetMemory(str);
              strcpy(str, "hello world");
              printf(str);
       }
       问运行Test 函数会有什么样的结果?他给出的参考答案是程序崩溃。因为GetMemory 并不能传递动态内存,Test 函数中的 str 一直都是 NULL。strcpy(str, "hello world");将使程序崩溃。
    在理解了指针变量是按值传递后,这道题目就会迎刃而解。
原创粉丝点击