I have a function that I'm using to build a string array. Inside the function i can print the array no worries however the program returns from the called function, the array (arr) remains NULL. How do I get the data out of the array ?
Thanks.
main(){
char **arr = NULL;
funct(arr);
printf("%s\n", arr[2];
}
funct(char **arr){
arr = malloc(10*sizeof(char *));
arr[1...n] = calloc(SIZE, sizeof(char));
// Add data to array
}
I can see several problemens in your code:
printf("%s\\n", arr[2];
you forgot a closing )
arr
variable local to the main
function is never initialized. In C, parameters are passed by value meaning that you are passing the NULL
pointer to your function and inside this function, the local pointer arr
is allocated but not the one of the main
function. The solution is to allocate the array in the main
function and pass a pointer to the array and the size to the function that fills it:
main(){
char **arr = malloc(10*sizeof(char *));
funct(arr, 10);
printf("%s\n", arr[2]);
}
funct(char **arr, int size){
// Add data to array
arr[0] = "first data";
....
arr[size -1] = "last data";
}
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.