I was practicing C programming and trying to create a 2D array with fixed rows, but variable columns. So, I used "array of pointers" concept i.e. I created an array such as int* b[4].
This is the code which was written:
#include <stdio.h>
int main(void) {
int* b[4];
int c[]={1,2,3};
int d[]={4,5,6,7,8, 9};
int e[]={10};
int f[]={11, 12, 13};
b[0]=c;
b[1]=d;
b[2]=e;
b[3]=f;
//printing b[0][0] to b[0][2] i.e. c[0] to c[2]
printf("b[0][0]= %d\tb[0][1]=%d\tb[0][2]=%d\n", b[0][0], b[0][1], b[0][2]);
//printing b[1][0] to b[1][5] i.e. d[0] to d[5]
printf("b[1][0]= %d\tb[1][1]=%d\tb[1][2]=%d\tb[1][3]=%d\tb[1][4]=%d\tb[1][5]=%d\n", b[1][0], b[1][1], b[1][2], b[1][3], b[1][4], b[1][5]);
//printing b[2][0] i.e. e[0]
printf("b[2][0]= %d\n", b[2][0]);
//printing b[3][0] to b[3][2] i.e. f[0] to f[2]
printf("b[3][0]= %d\tb[3][1]=%d\tb[3][2]=%d\n", b[3][0], b[3][1], b[3][2]);
return 0;
}
and the output was as expected:
b[0][0]= 1 b[0][1]=2 b[0][2]=3
b[1][0]= 4 b[1][1]=5 b[1][2]=6 b[1][3]=7 b[1][4]=8 b[1][5]=9
b[2][0]= 10
b[3][0]= 11 b[3][1]=12 b[3][2]=13
So, I think memory has been allocated this way:
But, question chimes in when this code is executed:
#include <stdio.h>
int main(void) {
int* b[4];
int c[]={1,2,3};
int d[]={4,5,6,7,8, 9};
int e[]={10};
int f[]={11, 12, 13};
b[0]=c;
b[1]=d;
b[2]=e;
b[3]=f;
int i, j;
for (i=0; i<4; i++)
{
for (j=0; j<7; j++)
{
printf("b[%d][%d]= %d ", i, j, b[i][j]);
}
printf("\n");
}
return 0;
}
And the output is something unusual:
b[0][0]= 1 b[0][1]= 2 b[0][2]= 3 b[0][3]= 11 b[0][4]= 12 b[0][5]= 13 b[0][6]= -1079668976
b[1][0]= 4 b[1][1]= 5 b[1][2]= 6 b[1][3]= 7 b[1][4]= 8 b[1][5]= 9 b[1][6]= -1216782128
b[2][0]= 10 b[2][1]= 1 b[2][2]= 2 b[2][3]= 3 b[2][4]= 11 b[2][5]= 12 b[2][6]= 13
b[3][0]= 11 b[3][1]= 12 b[3][2]= 13 b[3][3]= -1079668976 b[3][4]= -1079668936 b[3][5]= -1079668980 b[3][6]= -1079668964
One can observe that b[0][i] continues seeking values from b[3][i], array b[2][i] continues seeking values from b[0][i] followed by a[3][i], array b[3][i] and b1[i] terminate.
Every time when this program is executed, the same pattern is followed. So, is there something more on the way memory is allocated, or is this a mere co-incidence?
b[0]=c;, what is it you think is being stored inb[0]? If you try to iteratej > 2what happens? You must have some way of not attempting to read beyond the ends of space allocated forc, d, e & f. Since they differ in size, you either have to specifically limit your iteration to the appropriatesizeof each, or have some other way of signifying the end of data.gcc -Wall -Wextra -g). Then use the debugger (gdb). Beware of undefined behavior