Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

how to use flexible array in C to keep several values?

I have the following code:

typedef struct
{
   int name;
   int info[1]; 
} Data;

then I have five variables:

int a, b, c, d, e;

how can I use this as a flexible array to keep all the values of the five variables?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To do this properly, you should declare the flexible array member as an incomplete type:

typedef struct
{
   int name;
   int info[]; 
} Data;

Then allocate memory for it dynamically with

Data* data = malloc(sizeof(Data) + sizeof(int[N]));

for(int i=0; i<N; i++)
{
  data->info[i] = something; // now use it just as any other array
}

EDIT

Ensure that you are using a C99 compiler for this to work, otherwise you will encounter various problems:

If you allocate an array of length 1, then you will malloc 1 item for the first element of the array together with the struct, and then append N bytes after that. Meaning you are actually allocating N+1 bytes. This is perhaps not what one intended to do, and it makes things needlessly complicated.

(To solve the above problem, GCC had a pre-C99 extension that allowed zero-length arrays, which isn't allowed in standard C.)

Pre-C99, or in any other context than as a flexible array member, C doesn't allow incomplete array types as the one shown in my code.

C99 guarantees that your program is well-defined when using a flexible array member. If you don't use C99, then the compiler might append "struct padding" bytes between the other struct members and the array at the end. Meaning that data->info[0] could point at a struct padding byte and not at the first item in your allocated array. This can cause all kinds of weird, unexpected behavior.

This is why flexible array members were called "struct hack" before C99. They weren't reliable, just a dirty hack which may or may not work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...