這很奇怪,因爲我以前做過,但它只是不工作。我有這樣的結構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