一个结构必须有一个大小? [英] a struct must have a size?

查看:71
本文介绍了一个结构必须有一个大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

如果定义struct,必须给定尺寸吗?例如200.

Hi all,

If I define a struct, must have given a size? As in example is 200.

struct	LibCont_dat LCdat[200];


如果我希望struct的大小不受限制,该怎么办?

在此先感谢.


What can I do if I wish to have an unlimited size of struct?

Thanks in advance.

推荐答案

那没有定义结构的大小-结构定义做到了.
该代码的作用是声明一个结构数组-其中200个-与
That doesn''t define a size for the struct - the struct definition does that.
What that code does is declare an array of structs - 200 of them - in the same way that
int ar[100];

定义一个数组100个整数.

如果您的意思是我可以在不指定元素数量的情况下定义一个数组,并且该数组可以是我想要的任何大小吗?"那就不要.声明数组时,必须始终说出需要多少个元素.

如果您想要一个存储结构,其中的元素数量不固定并且可以随时添加新元素,那么建议您使用链接列表代替.

Defines an array of 100 integers.

If what you mean is "can I define an array where I do not specify the number of elements and it can be any size I want?" then no. You must always say how many elements you need when you declare the array.

If you want a storage structure where the number of elements is not fixed and new ones can be added at any time, I suggest you have a look at using a linked list instead.


您的代码甚至都不会编译.

你可以做类似的事情.这是一种原始方法,非常流行的是Windows API:

Your code won''t even compile.

You can do something like that. Here is one primitive method, pretty much popular is Windows API:

struct VariableSizeStructure {
    int someData;
    //...
    int Array[1]; //it can only come at the end
};



要使用此结构,请分配一些比该结构的大小更多的堆内存.例如,如果需要N元素,则通过索引0N-1分配大小sizeof(int) * (N - 1) + sizeof(VariableSizeStructure)和索引Array.



如果在新开发中进行代码设计,我绝不会推荐这种类型.仅仅因为某些API使用了此技术就很好了,但是实践本身很烂.不要在您自己的代码设计中使用它!

我非常感谢斯蒂芬(Stephan)的宝贵意见.显然,最初我没有提到这种方法的危险,现在就不迟了. :-)

—SA



To use this structure, allocate some heap memory more than the size of the structure. For example, if you need N elements, allocate the size sizeof(int) * (N - 1) + sizeof(VariableSizeStructure) and index Array by indices 0 to N-1.



I no way recommend this kind if code design in new development. This technique is good to know just because some APIs use it, but the practice itself is rotten. Don''t use it in your own code design!

I really appreciate the valuable comment by Stephan below. Apparently, originally I failed to mention the danger of this approach, not to late to do it now. :-)

—SA


您发布的代码定义了一个包含200个类型为LibCont_dat的元素的数组(它对struct的大小没有任何作用).

The code you posted define an array with 200 elements of type LibCont_dat (it does nothing to the size of the struct).

如果您要扩展数组,请尝试使用 vector 列表.

If you want an expandable array try to use vector or list.


这篇关于一个结构必须有一个大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆