user234159 user234159 - 1 month ago 7
C Question

A pointer to an array of struct segmentation faults in local scope (C)

I want to pass a pointer of array into a C function but I keep getting segmentation fault.

So the gist is ...

I have a structure:

typedef struct A {
int cost;
} B


In the main file:

static B (*arr_p)[] = NULL;
static B arr[30];

void foo(B **item)
{
printf("cost %d\n",(*item)[0].cost); // seg fault 11 :(
}

int main(int argc, char **argv)
{
arr_p = &arr;
(*arr_p)[0].cost = -1;
printf("Cost %d\n", (*arr_p)[0].cost); // works
foo((B **) arr_p);
}


Is there a way to deal with this pesky seg fault?

Answer

You are passing a pointer to an array to foo. You should change the definition of foo to accept a pointer to an array.

Change

void foo(B **item)
{
   printf("cost %d\n",(*item)[0].cost); // seg fault 11 :(
} 

to

void foo(B (*item)[])
{
   printf("cost %d\n",(*item)[0].cost); // seg fault 11 :(
} 

The problem was masked because of the cast in foo((B **) arr_p); Without the cast you get a warning on that line. It is generally not a good idea to typecast away a warning like this. In this case, it lead to a segmentation fault.