The notation with []
in a structure is a 'flexible array member' (FAM). Your structure contains a FAM of type int *
, so the values in the array are pointers to int
. You said you want an array of int
; that would be int data[];
.
According to the C standard, you can't initialize the FAM portion of a structure with a FAM. You could initialize the rest of the structure, but the FAM component would be empty, and there would be no way to add a FAM component to that structure.
You would need to do something like this — dynamically allocating the structure and the space for the array:
struct structure
{
char *name;
size_t size;
int data[];
};
int data[] = { 0, 1 };
struct structure *value = malloc(sizeof(*value) + sizeof(data));
if (value != 0)
{
value->name = "Some name";
value->size = sizeof(data) / sizeof(data[0]);
memcpy(value->data, data, sizeof(data));
…code using value…
free(value);
}
I added the size
member to the structure since code using it would need to know the size of the array somehow.
The following code demonstrates that GCC allows initialization of a FAM unless you tell it to follow the standard pedantically:
#include <stddef.h>
struct structure
{
char *name;
size_t size;
int data[];
};
struct structure value = { "Some name", 2, { 0, 1 } };
GCC (tested with 6.3.0 on a Mac running macOS Sierra 10.12.3) allows the initialization unless you tell it to be pedantic:
$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -c fam13.c
$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -pedantic -c fam13.c
fam13.c:10:44: error: initialization of a flexible array member [-Werror=pedantic]
struct structure value = { "Some name", 2, { 0, 1 } };
^
fam13.c:10:44: note: (near initialization for ‘value.data’)
cc1: all warnings being treated as errors
$
It would work similarly with the variable definition inside a function.