Hi guys,
this is a somewhat philosophical question.
I was searching for a way to minimize memory usage in an embedded system and come up with this solution:
Code:
#include <stdio.h>
int main()
{
char* t[]={"abc","d","ef"}; // Variable length 2d array
int i;
for (i=0; i<9; i++)
{
printf("%d,",t[0][i]); // Shows bytes in array
}
printf("\n");
printf("%s\n",t[0]); // Shows first string
printf("%s\n",t[1]); // Shows second string
printf("%s\n",t[2]); // Shows third string
printf("\n");
return 0;
}
Here is the output for this code:
Code:
sh-4.3$ gcc -o main *.c
sh-4.3$ main
97,98,99,0,100,0,101,102,0,
abc
d
ef
sh-4.3$
As you can see, the compiler does not created a 3x3 array, but an array with 3 elements, where the first is 4 bytes long, the second is 2 bytes long, and the third is 3 bytes long. Every string has a zero to finalize it.
Despite this strange format, a reference to a given index works fine. You can get the second element with t[1].
Here is my question: I always thought C finds an element in a 2d array by multiplying the given references like this:
Code:
If I have t[5][5],
t[3][4] == t[0][3*5+4]
But how C finds an element in this variable length 2d array that I described here?