c - 找到编号。结构数组中的元素?

标签 c

这很奇怪,因为我以前做过但它不起作用。我有一个像这样的结构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之前,我需要获取编号。 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 的值?

最佳答案

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

关于c - 找到编号。结构数组中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9170643/

相关文章:

c - c中的事件驱动设计

c - 程序C中的意外结果

C中循环条件下的逗号运算符

php - 由 PHP 执行的 C 应用程序在执行完成之前不会在浏览器上显示输出

c - 静默安装 winpcap

c - 不同scanf格式的区别

c - 指向整数数组的指针

c - Malloc 改变 C 中的值

c - 向不透明句柄添加 const-ness

c - C 中随机数生成的 rand%100 问题