指针传递

 1 void vGetMemory(char * pc)
 2 {
 3     pc = (char *)malloc(100);
 4 }
 5 
 6 void vTest(void)
 7 {
 8     char * pcStr = NULL;
 9     vGetMemory(pcStr);
10     strcpy(pcStr, "hello world");
11     printf(pcStr);
12 }

这段代码不能够运行,会奔溃掉。

因为vGetMemory是值拷贝,导致了pcStr一直都是NULL。

改为:

 1 #include <iostream>
 2 #include <malloc.h>
 3 using namespace std;
 4 
 5 void vGetMemory(char ** ppc)
 6 {
 7     *ppc = (char *)malloc(100);
 8 }
 9 
10 int main()
11 {
12     char * pcStr = NULL;
13     vGetMemory(&pcStr);
14     strcpy(pcStr, "hello world");
15     printf(pcStr);
16     return 0;
17 }
My Github Blog: mdgsf.github.io
原文地址:https://www.cnblogs.com/mdgsf/p/4141508.html