Hello, I am not sure why I am not able to print member structure member aa. Can someone please help? Code and output below:
Code:
#include <ansi_c.h>
// Structuer passing example
typedef struct
{
char t[10];
int w, h, a;
char *aa;
} area; // area is declared to be of type struct
void assign(void); // prototypes
area table[20]; // declare an array of 20 area's
area (*p)[20] = &table; // declare and define pointer-to-array of 20 area's
void assign() // use it
{
char str[10],str2[10];
for(int i=0; i<20; i++)
{
sprintf(str,"T%d\0",i);
strcpy((*p)[i].t,str);
(*p)[i].w = i; // dereference p to get to table,
// [i] to access i-th structure and
// .w to get the w member of it
(*p)[i].h = i;
(*p)[i].a = (*p)[i].w*(*p)[i].h;
sprintf(str2,"A%d\0",i);
(*p)[i].aa = str2;
printf("aa[%d]=%s\n",i,(*p)[i].aa);
}
}
int main(void)
{
assign(); // initial table
if(&p != NULL)
{
printf("No. TT W * H = Area AA\n========================\n");
for(int j=0; j<20; j++)
{
printf("[%2d] %-3s %2d %2d %3d %3s\n",j, (*p)[j].t,(*p)[j].w,(*p)[j].h,(*p)[j].a,(*p)[j].aa); // why doest this work aa (prints garbage)?
}
}
else
printf("pTable (= NULL) not pointing to anything (i.e. has not been intiaialized\n");
getchar();
return 0;
}
result printed:
aa[0]=A0
aa[1]=A1
aa[2]=A2
aa[3]=A3
aa[4]=A4
aa[5]=A5
aa[6]=A6
aa[7]=A7
aa[8]=A8
aa[9]=A9
aa[10]=A10
aa[11]=A11
aa[12]=A12
aa[13]=A13
aa[14]=A14
aa[15]=A15
aa[16]=A16
aa[17]=A17
aa[18]=A18
aa[19]=A19
No. TT W * H = Area AA
========================
[ 0] T0 0 0 0 H?ÎhO
XhH?Îh?
[ 1] T1 1 1 1 H?ÎhO
XhH?Îh?
[ 2] T2 2 2 4 H?ÎhO
XhH?Îh?
[ 3] T3 3 3 9 H?ÎhO
XhH?Îh?
[ 4] T4 4 4 16 H?ÎhO
XhH?Îh?
[ 5] T5 5 5 25 H?ÎhO
XhH?Îh?
[ 6] T6 6 6 36 H?ÎhO
XhH?Îh?
[ 7] T7 7 7 49 H?ÎhO
XhH?Îh?
[ 8] T8 8 8 64 H?ÎhO
XhH?Îh?
[ 9] T9 9 9 81 H?ÎhO
XhH?Îh?
[10] T10 10 10 100 H?ÎhO
XhH?Îh?
[11] T11 11 11 121 H?ÎhO
XhH?Îh?
[12] T12 12 12 144 H?ÎhO
XhH?Îh?
[13] T13 13 13 169 H?ÎhO
XhH?Îh?
[14] T14 14 14 196 H?ÎhO
XhH?Îh?
[15] T15 15 15 225 H?ÎhO
XhH?Îh?
[16] T16 16 16 256 H?ÎhO
XhH?Îh?
[17] T17 17 17 289 H?ÎhO
XhH?Îh?
[18] T18 18 18 324 H?ÎhO
XhH?Îh?
[19] T19 19 19 361 H?ÎhO
XhH?Îh?