如何在C中使用灵活数组来保留多个值? [英] how to use flexible array in C to keep several values?

查看:32
本文介绍了如何在C中使用灵活数组来保留多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

那么我有五个变量:

int a, b, c, d, e;

如何使用它作为一个灵活的数组来保存五个变量的所有值?

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

推荐答案

要正确执行此操作,您应该将灵活数组成员声明为不完整类型:

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

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

然后使用

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
}

<小时>

编辑

请确保您使用的是 C99 编译器,否则您会遇到各种问题:

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

如果你分配一个长度为1的数组,那么你会为数组的第一个元素和结构体一起malloc 1项,然后在之后追加N个字节.这意味着您实际上正在分配 N+1 个字节.这可能不是人们想要做的,它使事情变得不必要地复杂.

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.

(为了解决上述问题,GCC 有一个 C99 之前的扩展,允许零长度数组,这在标准 C 中是不允许的.)

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

C99 之前,或在任何其他上下文中而不是作为灵活的数组成员,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 保证您的程序在使用灵活数组成员时定义良好.如果您不使用 C99,那么编译器可能会在其他结构成员和最后的数组之间附加结构填充"字节.这意味着 data->info[0] 可以指向结构填充字节,而不是分配的数组中的第一项.这可能会导致各种奇怪的、意外的行为.

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.

这就是为什么在 C99 之前,灵活的数组成员被称为struct hack".它们不可靠,只是一个肮脏的黑客,可能有效,也可能无效.

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.

这篇关于如何在C中使用灵活数组来保留多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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