problem
以下代码的输出时什么?
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void getmen(char* p)//把 char*看成一种数据类型类比int
{
p = (char *)malloc(100);
}
int main()
{
char *p = NULL;
getmen(p);
strcpy_s(p, 10, "hello");
printf("%s", p);
return 0;
}
getmen(p)传过去的是p的值,并没有穿过去p的地址。修改值传的是形参,不会影响主函数p的值。p所指向地址还是为NULL。运行时会报错,因为strcpy要求目标地址不能为NULL。
因此要改变主函数中p的值,必修要将指向p的地址传过去。因为p本身是一个指针,所以要用二级指针,即指向指针的指针来修改。
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void getmen(char **pp)
{
*pp = (char *)malloc(100);
}
int main()
{
char *p = NULL;
getmen(&p);
strcpy_s(p, 10, "hello");
printf("%s", p);
return 0;
}