2012-02-07 42 views
1

这很奇怪,因为我以前做过,但它只是不工作。我有这样的结构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?

尽管我已经找到了几个解决方法来确定一个数组结构的大小。

  1. 获取否。从主叫方元素和

  2. 另一个是强制获得最后的结构元素作为{0,0,0,NULL}然后在write() 检查它的存在,并进一步停止扫描frame_array

但都取决于调用者,你不能信任的东西。 那么真正的问题在哪里。我怎么能确定num_frames的价值?

回答

4

将数组作为指针传递给函数,因此您看到的8个字节实际上是指针的大小(假设您的位置是64位),而不是原始数组的大小。无法检索指向数组的实际大小,因此您必须将其分别传递给该函数。

+0

是的,我想那样我将不得不与大小合格。但是我提到的两种方法中哪一种更好? – tnx1991 2012-02-07 03:48:41

+0

@ tnx1991:这两种方法都很好。选择最适合你的情况。 – casablanca 2012-02-07 03:50:35

1

将数组作为参数传递给函数时,无法知道数组的大小。您需要传递数组中的元素数量。

short int write_frames(xmp_frame frame_array[], int num_frames,FILE *outfp) 
{ 
    for(int i=0; i < num_frames; i++) 
     // write frame_array[i] 
} 
0

你可以利用这个功能做到这一点:

size_t _msize(void *memblock); 

,并调用它,当你想与你的结构数组的指针。

+0

请注意,这是Microsoft特定的功能。 – dbush 2017-06-15 20:21:34