[英]Struct with an array as variable in c
i need to create a data type (struct in this case) with an array as a property. 我需要创建一个数据类型(在本例中为struct),并将数组作为属性。 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].
例如“int values []”将要求我在括号中输入数字,例如值[256]。 Th3 256 should be specified wen the structure is initialised.
应该在结构初始化时指定Th3 256。 Is there a way I get around this?
有没有办法解决这个问题?
typedef struct
{
int values[]; //error here
int numOfValues;
} Queue;
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.
如果需要具有可变长度的数组,则必须动态分配内存。
typedef struct {
int *values;
int numOfValues;
} Queue;
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:
在struct的初始化中,将指针指向一个用malloc分配的内存区域:
Queue q;
q.numOfValues = 256;
q.values = malloc(256 * sizeof(int));
Remember to check the return value for a NULL
pointer and free()
any dynamically allocated memory as soon as it isn't used anymore. 请记住,只要不再使用,就检查
NULL
指针的返回值和free()
任何动态分配的内存。
#include<stdio.h>
#include<stdlib.h>
typedef struct Queue {
int numOfValues;
int values[0];
} Queue_t;
int main(int argc, char **argv) {
Queue_t *queue = malloc(sizeof(Queue_t) + 256*sizeof(int));
return (1);
}
This way you can declare 'variable length arrays'. 这样你就可以声明'可变长度数组'。 And you can access your array 'values' with queue->values[index]
您可以使用queue-> values [index]访问数组'values'
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 编辑:当然你需要确保一旦你释放你考虑到你已经分配的'n * sizeof(int)'和sizeof(Queue_t),其中n = 256在上面的例子中HTH
You can use C99 features like VLA, eg 您可以使用像VLA这样的C99功能,例如
int main()
{
int len=1234;
struct MyStruct {int i,array[len];} var;
var.array[0]=-1;
var.array[len-1]=1;
printf( "%i %i %lu", var.array[0],var.array[len-1],(unsigned long)sizeof(var) );
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.