转载自:https://blog.csdn.net/qq_22525091/article/details/80116128
code
#include<stdio.h>
#include<stdlib.h>
void GetMemory(char *p, int num)
{
p = (char *)malloc(sizeof(char) * num);
}
void Test(void)
{
char *str = NULL;
GetMemory(str, 100); // str 仍然为 NULL
printf("address str:%p \n", str);
// strcpy(str, "hello"); // 运行错误
}
void getsum(int sum, int n)
{
for (int i = 0; i < n; i++)
{
sum += i;
}
}
void Test2()
{
int sum = 0;
getsum(sum, 10);
printf("sum value:%d \n", sum);
}
int main(int argc, char** argv){
Test();
Test2();
return 0;
}
解释:
Test
是声明了一个指针,然后到子函数中用malloc进行内存申请,但是后面打印的时候发现,返回的结果为null。这里又写了Test2,将一个int变量作为形参传入,Test只是将一个指针变量作为形参传入,- 这里
Test
和Test2
差不多的。传入的变量在子函数都会新建一个副本,副本改变了,原来的不会改变。如果要改变原来的值,需要使用指针。