找到号码。结构数组中的元素?

Posted

技术标签:

【中文标题】找到号码。结构数组中的元素?【英文标题】:Find the no. of elements in an array of structs? 【发布时间】:2012-02-07 03:33:57 【问题描述】:

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

虽然我找到了一些解决方法来确定结构数组的大小。

    获取编号。来自调用者和

    的元素

    另一个是强制获取最后一个结构元素为0,0,0,NULL,然后 在write() 中检查它是否存在并停止进一步扫描frame_array

但两者都依赖于调用者,这是你不能信任的。 那么真正的问题在哪里。我如何确定num_frames 的值?

【问题讨论】:

【参考方案1】:

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

【讨论】:

是的,我想那么我将不得不通过传递大小。但是我提到的两种方法中哪一种更好? @tnx1991:任何一种方法都可以。选择最适合您的情况。【参考方案2】:

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

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]

【讨论】:

【参考方案3】:

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

size_t _msize(void *memblock);

并在需要时使用结构数组指针调用它。

【讨论】:

注意这是微软特有的功能。

以上是关于找到号码。结构数组中的元素?的主要内容,如果未能解决你的问题,请参考以下文章

如何删除mongodb中的数组元素?

如何删除mongodb中的数组元素?

数据结构——数组

为啥我的数组列表只更改一个元素中的数据?

数据结构--单调栈结构

查找数组中的 K 个最小元素