本文介绍了如何使用灵活的阵列中的C到保持几个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的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?

推荐答案

要正确地做到这一点,你应该声明柔性阵列成员作为一个不完全类型:

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
}


修改

请确保您使用的是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有$ P $对 - 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.)

pre-C99,或任何其他方面不是作为一个灵活的阵列成员,C不允许不完整的数组类型在我的code所示。

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,那么编译器可能追加其他结构成员,并在年底阵列之间结构填充字节。这意味着数据 - &GT;信息[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之前被称为结构黑客。它们是不可靠的,只是一个肮脏的黑客可能或可能不工作。

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到保持几个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 16:16