#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char *p)
{
p=(char *)malloc(100);
strcpy(p,"hello world");
}
int main (void)
{
char *str=NULL;
getmemory(str);
printf("%s\n",str);
free(str);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char *p)
{
p=(char *)malloc(100);
strcpy(p,"hello world");
}
int main (void)
{
char *str=NULL;
getmemory(str);
printf("%s\n",str);
free(str);
return 0;
}
因为参数仅仅是传值,函数内不能通过改变参数值去改变函数外的参变量。
函数内可以通过以下任一方法将值传递到函数外的变量:
返回值
传参数的地址,即指向参数的指针,函数内修改指针指向的内容
将参数指定为引用类型(这是c++语法)