[英]C Programming: malloc() inside a function
I would like to allocate memory in a function and then use that space in the main(). 我想在一个函数中分配内存,然后在main()中使用该空间。
All is fine in the function, but I never can access the data in the main(). 在该函数中一切都很好,但是我永远无法访问main()中的数据。
There are two memory allocation instructions for simulating a two dimensionnal array of chars 有两个内存分配指令可用于模拟char的二维数组
Here's my code: 这是我的代码:
#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;
}
Output is 输出是
networks before call:0x0
networks in function:0x7feb65c02af0
networks after call:0x0
Segmentation fault: 11
The following needs to be fixed: 需要修复以下问题:
int getNetworks(char ***networks)
as it is a pointer to an array of pointers to chars. 因为它是指向字符数组的指针。 (You can also write this as
(您也可以将其写为
char **networks[]
). char **networks[]
)。
In the function you must first dereference the pointer to work on the parent's variable: 在函数中,您必须首先取消引用指针以使用父级变量:
*networks = malloc(5 * sizeof(char*));
(*networks)[0] = (char*) malloc(4);
In main, your declaration is correct, however, you must call as: 总的来说,您的声明是正确的,但是,您必须调用:
getNetworks(&networks);
so the function can work on the parent's variable. 因此该函数可以作用于父变量。
There are many problems in your code, I will not comment them, but propose you this solution: 您的代码中有很多问题,我将不予评论,但为您提出以下解决方案:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char** getNetworks(int *n)
{
int count = 5;
char ** networks = malloc(count * 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");
*n = count;
return networks;
}
int main ()
{
char **networks = NULL;
int nbNetworks;
printf("networks before call:%p\n", networks);
networks = getNetworks(&nbNetworks);
printf("networks after call:%p\n", networks);
for (int i=0; i < nbNetworks; i++) {
printf ("%s\n", networks[i]);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.