achuthpnr
March 13th, 2015, 12:06 PM
Im trying to learn the concept of flexible arrays in C. I have a struct containging an array, the length of which is unknown at the time of compilation or is an input parameter.
Everything goes well so far, until I run the program.
It appears that the extra memory allocated to store the array info gets added to the end of the struct. Hence the ouput reads the contents of other members instead of the intended value.
Is there any way to make the array elements added as if it is a predefined structure with a fixed array size, so that it coule be correctly printed?
Here is the program I have
#include<stdio.h>
#include<stdlib.h>
struct table_type
{
unsigned int a;
unsigned int b;
unsigned int c;
unsigned int d;
unsigned int e[];
};
struct table_type *table;
int main()
{
unsigned int i,j;
unsigned int N=6; // Intended to be read from input
table=(struct table_type *)calloc(N,(sizeof(struct table_type)+N*sizeof(unsigned int)));
for(i=0;i<N;i++)
{
table[i].a=i;
table[i].b=i+10;
table[i].c=i+100;
table[i].d=i+1000;
for(j=0;j<N;j++)
{
table[i].e[j]=i+j;
}
}
for(i=0;i<N;i++)
{
printf("\n");
for(j=0;j<N;j++)
printf("i=%u j=%u k=%u\n",i,j,table[i].e[j]);
}
return 0;
}
The question is how do I properly access table[i].[j]?
Everything goes well so far, until I run the program.
It appears that the extra memory allocated to store the array info gets added to the end of the struct. Hence the ouput reads the contents of other members instead of the intended value.
Is there any way to make the array elements added as if it is a predefined structure with a fixed array size, so that it coule be correctly printed?
Here is the program I have
#include<stdio.h>
#include<stdlib.h>
struct table_type
{
unsigned int a;
unsigned int b;
unsigned int c;
unsigned int d;
unsigned int e[];
};
struct table_type *table;
int main()
{
unsigned int i,j;
unsigned int N=6; // Intended to be read from input
table=(struct table_type *)calloc(N,(sizeof(struct table_type)+N*sizeof(unsigned int)));
for(i=0;i<N;i++)
{
table[i].a=i;
table[i].b=i+10;
table[i].c=i+100;
table[i].d=i+1000;
for(j=0;j<N;j++)
{
table[i].e[j]=i+j;
}
}
for(i=0;i<N;i++)
{
printf("\n");
for(j=0;j<N;j++)
printf("i=%u j=%u k=%u\n",i,j,table[i].e[j]);
}
return 0;
}
The question is how do I properly access table[i].[j]?