0

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);
4
  • lol before I posted I censored the code on my machine but I forgot to change it here. Nice catch thanks. Commented Feb 19, 2015 at 2:31
  • I am surprised you didn't get any compiler errors. names[i] is not compatible with char* []. You should change foo(char *bar[]) to foo(char *bar). Commented Feb 19, 2015 at 2:35
  • I don't get any errors. I run it in code blocks and the exe crashes. It's super frustrating because I never have any leads for the errors. Commented Feb 19, 2015 at 2:36
  • names is not an array of pointers. Commented Feb 19, 2015 at 2:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this works but it just prints out the first element in the array. How can I make it print out any given element in the array?
You can print bar[0], bar[1], etc. You can use a for loop in main to do that. You can also pass numbOfPoints to foo and put the for loop in foo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.