I would like to allocate memory in a function and then use that space in the main().
All is fine in the function, but I never can access the data in the main().
There are two memory allocation instructions for simulating a two dimensionnal array of chars
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[]
).
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.