【发布时间】:2019-08-07 08:06:51
【问题描述】:
我想在函数中分配内存,然后在 main() 中使用该空间。
函数中一切正常,但我永远无法访问 main() 中的数据。
有两条内存分配指令用于模拟二维字符数组
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getNetworks(char **networks) {
networks = malloc(5 * sizeof(char*));
printf("networks in function:%p\n", networks);
networks[0] = (char*) malloc(4);
strcpy(networks[0], "aaa");
networks[1] = (char*) malloc(3);
strcpy(networks[1], "bb");
networks[2] = (char*) malloc(5);
strcpy(networks[2], "cccc");
networks[3] = (char*) malloc(6);
strcpy(networks[3], "ddddd");
networks[4] = (char*) malloc(2);
strcpy(networks[4], "e");
return 5;
}
int main ()
{
char **networks = NULL;
int nbNetworks;
printf("networks before call:%p\n", networks);
nbNetworks = getNetworks(&*networks);
printf("networks after call:%p\n", networks);
for (int i=0; i<=nbNetworks-1; i++) {
printf ("%s\n", networks[i]);
}
return 0;
}
输出是
networks before call:0x0
networks in function:0x7feb65c02af0
networks after call:0x0
Segmentation fault: 11
【问题讨论】:
-
那应该是
*networks = malloc(5 * sizeof(char*));因为你要修改父级的变量,而不是栈上的value参数。 -
getNetworks(&*networks);闻起来很臭。
-
在处理父数组时,它应该是
(*networks)[0] = (char*) malloc(4);。
标签: c arrays function pointers malloc