1

I have a struct:

struct Thing {
    int id;
}

Then I create an array of Things:

struct Thing *a;
a = (struct Thing *) malloc(sizeof(struct Thing));
a->id = 1;

struct Thing *b;
b = (struct Thing *) malloc(sizeof(struct Thing));
b->id = 2;

struct Thing *array[] = {a,b};

I check the size of the array and is 2. I check the size of array by:

printf("%d",sizeof(array)/sizeof(array[0]));

I also have a function that takes in an array of Things:

void function(struct Thing *array[]) {
    //do stuff
}

Then I pass in the array to function:

function(array);

Inside the function, the size of the array is 1. Can someone point to me where did I go wrong and why is the size of the array 1 inside of the function?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
drum
  • 5,416
  • 7
  • 57
  • 91

2 Answers2

2

When you pass an array of any kind to a function, it decays to a pointer to the first element of this array.

void function(struct Thing *array[]) {
    //do stuff
}

Is just syntactic sugar for

void function(struct Thing** array) {
    //do stuff
}
Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • That explains why only the 1st element remains. – drum Feb 25 '13 at 07:41
  • @drum, both elements are still there, 2nd element can be accessed as `array[1]`. It is just that the data type has changed from array to pointer, and thus the behavior of `sizeof` with it. – Karthik T Feb 25 '13 at 07:42
  • No, both elements remain, but the pointer points only to the beginning of the array! You should be able to access the second index in the funtion without SEGFAULT. – bash.d Feb 25 '13 at 07:43
1

Your array-definition

struct Thing *array[] = {a,b};

should be

struct Thing array[] = {a,b};

then pass it to the function; the function should be declared

void function(struct Thing *array, int count) {
//do stuff
}

so you can pass the bounds of the array.

bash.d
  • 13,029
  • 3
  • 29
  • 42
  • 2
    `a` and `b` are pointers to struct and you are suggesting to initialize an array of structs with pointers to structs, how is that going to work? – Alexey Frunze Feb 25 '13 at 07:48
  • 1
    `struct Thing array[] = {*a,*b}`; – yuan Feb 25 '13 at 07:54
  • @ZhangYuan: Thank you! That was exactly the solution to my problem! You should post the answer and I'll accept it. – drum Feb 25 '13 at 08:00