这很奇怪,因为我以前做过,但它只是不工作。我有这样的结构xmp_frame
。找到没有。的结构数组中的元素?
typedef struct {
short int attr_dtype;
short int attr_code;
short int attr_len;
const char *attr;
}xmp_frame;
现在我创建的xmp_frame
数组,并使用它们,如:
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??"}
};
现在我有一个程序,基本上到的文件中写入frame_array
:
short int write_frames(xmp_frame frame_array[],FILE *outfp){
}
我写之前frame_array
我需要得到no。 frame_array[]
中的元素进行一些处理。因此,这是我们如何做到这一点(通常情况下):
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
}
当然,如果frame_array
是8个字节,frame_array[0]
是16个字节,然后num_frames
将是0。
但问题是如何能的大小一个数组比它的一个元素小?我听说过字节填充。
我没有太多的想法,如果它导致的问题。这里是我提到的其中一个链接: Result of 'sizeof' on array of structs in C?
尽管我已经找到了几个解决方法来确定一个数组结构的大小。
获取否。从主叫方元素和
另一个是强制获得最后的结构元素作为
{0,0,0,NULL}
然后在write()
检查它的存在,并进一步停止扫描frame_array
。
但都取决于调用者,你不能信任的东西。 那么真正的问题在哪里。我怎么能确定num_frames
的价值?
是的,我想那样我将不得不与大小合格。但是我提到的两种方法中哪一种更好? – tnx1991 2012-02-07 03:48:41
@ tnx1991:这两种方法都很好。选择最适合你的情况。 – casablanca 2012-02-07 03:50:35