2012-02-07 46 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