Reputation: 1094
I am trying to pass an array of pointers to strings (names) into a function (foo) and read from it. The below code produces a segmentation fault. Can someone please help me figure out why this code is resulting in a segmentation fault? I want to be able to pass the array names[][] through a function and work with the data like I would if I were using names[][] outside the function.
void foo(char *bar[]) {
printf("%s\n", bar[0]);
}
//---------------Main-------------
char args[][50] = {"quick", "brown", "10", "brown", "jumps", "5"};
int i = 0;
int numbOfPoints = (sizeof(args)/sizeof(args[0]))/3;
//array of all the locations. the number will be its ID (the number spot in the array)
//the contents will be
char names[numbOfPoints][100];
for(i = 0; i < numbOfPoints; i++) {
char *leadNode = args[i*3];
char *endNode = args[i*3 + 1];
char *length = args[i*3 + 2];
int a = stringToInt(length);
//add name
strcpy(names[i],leadNode);
}
//printing all the names out
for(i = 0; i < numbOfPoints; i++) {
printf("%s\n", names[i]);
}
foo(names);
Upvotes: 0
Views: 64
Reputation: 206567
The problem is the the argument type of foo
and the way you are calling it. The argument type of foo
, char* []
is not compatible with name
. I get the following warning in gcc 4.8.2 with -Wall
.
soc.c:35:4: warning: passing argument 1 of ‘foo’ from incompatible pointer type [enabled by default]
foo(names);
^
soc.c:5:6: note: expected ‘char **’ but argument is of type ‘char (*)[100]’
void foo(char *bar[]) {
Change foo
to:
void foo(char (*bar)[100]) {
printf("%s\n", bar[0]);
}
and all should be well.
Upvotes: 1