C 中以数组作为变量的结构
我需要创建一个数据类型(在本例中为结构),并将数组作为属性。我有一个初始化函数,可以初始化该数据结构并为数组指定指定的大小。现在的问题是在结构中声明数组。例如“int value[]”将要求我在括号中输入一个数字,例如values[256]。 Th3 256 应该在结构初始化时指定。我有办法解决这个问题吗?
typedef struct
{
int values[]; //error here
int numOfValues;
} Queue;
i need to create a data type (struct in this case) with an array as a property. I have an initialiser function that initialises this data structure and gives the array a specified size. The problem now is declaring the array in the struct. for example "int values[]" will require that I enter a number in the brackets eg values[256]. Th3 256 should be specified wen the structure is initialised. Is there a way I get around this?
typedef struct
{
int values[]; //error here
int numOfValues;
} Queue;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
结构必须具有编译时已知的固定大小。如果你想要一个可变长度的数组,你必须动态分配内存。
这样你就只将指针存储在结构中。在结构体的初始化中,您将指针分配给使用 malloc 分配的内存区域:
请记住检查
NULL
指针的返回值以及free()
任何动态分配的内存一旦不再使用。A struct must have a fixed size known at compile time. If you want an array with a variable length, you have to dynamically allocate memory.
This way you only have the pointer stored in your struct. In the initialization of the struct you assign the pointer to a memory region allocated with malloc:
Remember to check the return value for a
NULL
pointer andfree()
any dynamically allocated memory as soon as it isn't used anymore.这样你就可以声明“可变长度数组”。您可以使用queue->values[index]访问您的数组“值”
编辑:当然,您需要确保一旦释放,您就会考虑到您与sizeof一起分配的“n * sizeof(int)” (Queue_t) 上例中 n=256
华泰
This way you can declare 'variable length arrays'. And you can access your array 'values' with queue->values[index]
EDIT: Off course you need to make sure that once you free you take into account the 'n*sizeof(int)' you have allocated along with sizeof(Queue_t) where n=256 in the above example
HTH
您可以使用 VLA 等 C99 功能,例如
You can use C99 features like VLA, e.g.