关于华为的一道笔试题(传值和传引用)

来源:互联网 发布:浙江大学数据结构知乎 编辑:程序博客网 时间:2024/06/13 23:16
#include <stdio.h>  #include <stdlib.h>  void getmemory(char *p)  {    p=(char *) malloc(100);    strcpy(p,"hello world");  }  int main( )  {    char *str=NULL;    getmemory(str);//等于getmemory(char *p=str);你函数里p倒是获取了内存,但是str什么都没有,要传引用,    printf("%s/n",str);    free(str);    return 0;   }

这个程序的问题

程序崩溃,getmemory中的malloc 不能返回动态内存, free()对str操作很危险

可以更改为下面的程序:

#include <stdio.h>   #include <stdlib.h>   void getmemory(char **p)   {     *p=(char *) malloc(100);     strcpy(*p,"hello world");   }   int main( )   {     char *str=NULL;     getmemory(&str);     printf("%s/n",str);     free(str);     return 0;   } 

C语言是值传递,故在函数调用中修改的值,并不会返传至主调函数。所以原程序在getmemory函数中malloc获得的地址空间的首地址的值只在函数内部有效,函数调用结束后该值就丢失了

0 0
原创粉丝点击