1
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.

1 Answer 1

2

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};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.