Jason
Jason

Reputation: 21

Get the size of a nested array in C

char* alanina[] = {"alanina", "GCA","GCC","CGC","GCU"};
char* arginina[] = {"arginina", "AGA","AGG","CGA","CGC","CGG","CGU"};
char **aminoacids[] = {alanina,arginina};

printf("%i\n",(int)(sizeof(aminoacids[0]) / sizeof(**aminoacids[0]))); 

// the console display 8 and the correct answer is 5.

Upvotes: 1

Views: 120

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

once you put your arrays in an array of pointers like this:

char **aminoacids[] = {alanina,arginina};

you decay them into simple pointers. and you get sizeof(pointer)/sizeof(char) => 8 on your 64-bit compiler because your sizeof division uses a double ** as demominator instead of one (that's the second mistake)

If you did sizeof(aminoacids[0]) / sizeof(*aminoacids[0]) you'd get 1 as a result, for the same reason: aminoacids[0] has decayed to a pointer.

The only way to get 5 is sizeof(alanina)/sizeof(*alanina) because the array has not decayed and the compiler can provide its storage size.

An alternate way of computing the number of elements would be to introduce a convention to NULL terminate your arrays. Then you'd just scan the array for NULL and get the size that way.

{"alanina", "GCA","GCC","CGC","GCU",NULL};

Upvotes: 2

Related Questions