It's weird because I have done it before but it just is not working. I have a structure xmp_frame
like this.
typedef struct {
short int attr_dtype;
short int attr_code;
short int attr_len;
const char *attr;
}xmp_frame;
Now I create an array of xmp_frame
and use them like:
xmp_frame frame_array[]={
{1,2,strlen("Hello there"),"Hello there"},
{1,3,strlen("This is not working"),"This is not working"},
{0,3,strlen("But why??"),"But why??"}
};
Now I have a routine which basically writes the frame_array
in to file:
short int write_frames(xmp_frame frame_array[],FILE *outfp){
}
Before I write the frame_array
I need to get the no. of elements in frame_array[]
for doing some processing. So this is how we do it (generally):
short int write_frames(xmp_frame frame_array[],FILE *outfp) {
short intnum_frames=sizeof(frame_array) / sizeof(frame_array[0]);
/*But i get the value of num_frames as 0. I will print the outout of some debugging.*/
fprintf(stderr,"\n Size of frame_array : %lu",sizeof(frame_array)); //prints 8
fprintf(stderr,"\n Size of frame_array[0] : %lu",sizeof(frame_array[0])); //prints 16
fprintf(stderr,"\n So num. of frames to write : %d", (sizeof(frame_array))/(sizeof(frame_array[0]))); //prints 0
}
Of course if frame_array
is 8 bytes and frame_array[0]
is 16 bytes then num_frames
is going to be 0.
But the question is how can size of an array be smaller than one of its elements? I heard about byte padding.
I don't have much of an idea if it is causing the problem. Here is one of the links I referred to: Result of 'sizeof' on array of structs in C?
Although I have found a few workarounds to determine the size of an array of structs.
Get the no. of elements from the caller and
another is compulsorily get the last struct element as
{0,0,0,NULL}
and then inwrite()
check for it's presence and stop scanningframe_array
any further.
But both depend on the caller, something which you can't trust.
So where is the real problem. And how could I determine the value of num_frames
?