# Thread: Array with pointer to Structarray

1. ## Array with pointer to Structarray

Hi,

Code:
```#include <stdio.h>
#include <stdlib.h>

#define LENGTH(x) (sizeof(x)/sizeof(x[0]))

struct foo {
int a;
char* b;
};

struct foo bar[] = {
{1, "abc"}, {2, "def"}, {3, "ghj"}
};

struct foo baz[] = {
{1, "xyz"}
};

struct foo* array[] = {
bar, baz
};

int main(void) {
int i, j;

printf("%s\n", array[0][2].b);
printf("%d %d\n", (int)LENGTH(bar), (int)LENGTH(array[0]));

for(i = 0; i < LENGTH(array); i++)
for(j = 0; j < LENGTH(array[j]); j++)
printf("%d: %s\n", array[i][j].a, array[i][j].b);

return EXIT_SUCCESS;
}```
the bold macro call returns 0. I guess the complier knows the struct-array size only at compile time so my dynamic solution wont work. Any ideas for a solution without saving the array size?

Regards,
lwi

2. The problem is sort of what you describe, but not quite: it is because you are trying to take the length of a pointer object, and divide it by the size of the struct that the pointer points to. The LENGTH macro that you have ONLY works on real arrays, not on pointers to arrays.

In other words, sizeof(array[0]) is most likely 4 (on a 32-bit machine it is, on a 64-bit machine it is 8). sizeof(array[0][0]) which you then divide by is sizeof(foo) - which is either 8, 12 or 16 depending on the size of a pointer and the compiler's alignment padding. I'd expect EVERY architecture to have a struct of int and char * size to be bigger than the pointer to such a structure.

--
Mats

3. Of course you are right. I just figured out myself I cannot get the array-size when I only have a pointer to the array.

I guess the best solution would be to NUL-terminate my struct-array, however I dont know exactly how to do it, probably a new struct (
Code:
`struct { struct foo[] array; char nul; }`
)?

Regards,
lwi

4. Code:
```struct foo bar[] = {
{1, "abc"}, {2, "def"}, {3, "ghj"},{0,NULL}
};

struct foo baz[] = {
{1, "xyz"},{0,NULL}
};```

5. ## Thanks

Thanks, works perfectly.

Solution:
Code:
```#include <stdio.h>
#include <stdlib.h>

#define LENGTH(x) (sizeof(x)/sizeof(x[0]))

struct foo {
int a;
char* b;
};

struct foo bar[] = {
{1, "abc"}, {2, "def"}, {3, "ghj"}, {0, NULL}
};

struct foo baz[] = {
{1, "xyz"}, {0, NULL}
};

struct foo* array[] = {
bar, baz
};

int main(void) {
int i, j;

printf("%s\n", array[0][2].b);
printf("%d %d\n", (int)LENGTH(bar), (int)LENGTH(array[0]));

for(i = 0; i < LENGTH(array); i++)
for(j = 0; !(array[i][j].a == 0 && array[i][j].b == NULL); j++)
printf("%d: %s\n", array[i][j].a, array[i][j].b);

return EXIT_SUCCESS;
}```