Passing a string array to a function in C -
i learning c, explain why following code produces segmentation fault after printing first element of array?
what working code like?
#include <stdio.h> #include <stdlib.h> #include <string.h> #define elements 8 void make(char ***array) { *array = malloc(elements * sizeof(char *)); (*array)[0] = "test0"; (*array)[1] = "test1"; (*array)[2] = "test2"; (*array)[3] = "test3"; (*array)[4] = "test4"; (*array)[5] = "test5"; (*array)[6] = "test6"; (*array)[7] = "test7"; (*array)[8] = "test8"; } int main(int argc, char **argv) { char **array; make(&array); int i; (i = 0; < elements; ++i) { printf("%s\n", array[i]); free(array[i]); } free(array); return 0;
}
when put literal string in c++ "test0"
, stored in special memory location cannot modified. in line
(*array)[0] = "test0";
you're pointing char*
memory location, alright do. however, later, when call free(array[i]);
, attempting free same memory, no-no. in general, use free()
if have used malloc()
on same variable.
also, others have said, need allocate array of size 9, since you're using 9 elements.
Comments
Post a Comment