如何在 C 中的结构中包含动态数组? [英] How to include a dynamic array INSIDE a struct in C?

查看:43
本文介绍了如何在 C 中的结构中包含动态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,但一直无法找到一个必须很好问的问题的解决方案.这是我的代码:

I have looked around but have been unable to find a solution to what must be a well asked question. Here is the code I have:

 #include <stdlib.h>

struct my_struct {
    int n;
    char s[]
};

int main()
{
    struct my_struct ms;
    ms.s = malloc(sizeof(char*)*50);
}

这是gcc给我的错误:错误:灵活数组成员的无效使用

and here is the error gcc gives me: error: invalid use of flexible array member

如果我将结构中的 s 声明声明为

I can get it to compile if i declare the declaration of s inside the struct to be

char* s

这可能是一个更好的实现(指针算法比数组快,是吗?)但我认为在 c 中声明了

and this is probably a superior implementation (pointer arithmetic is faster than arrays, yes?) but I thought in c a declaration of

char s[]

char* s

推荐答案

你现在写的方式,曾经被称为struct hack",直到 C99 祝福它为灵活的数组成员".您收到错误的原因(可能无论如何)是它后面需要跟一个分号:

The way you have it written now , used to be called the "struct hack", until C99 blessed it as a "flexible array member". The reason you're getting an error (probably anyway) is that it needs to be followed by a semicolon:

#include <stdlib.h>

struct my_struct {
    int n;
    char s[];
};

当您为此分配空间时,您希望分配结构体的大小加上数组所需的空间量:

When you allocate space for this, you want to allocate the size of the struct plus the amount of space you want for the array:

struct my_struct *s = malloc(sizeof(struct my_struct) + 50);

在这种情况下,灵活的数组成员是一个 char 数组,并且 sizeof(char)==1,因此您不需要乘以它的大小,但就像您需要的任何其他 malloc 一样,如果它是其他类型的数组:

In this case, the flexible array member is an array of char, and sizeof(char)==1, so you don't need to multiply by its size, but just like any other malloc you'd need to if it was an array of some other type:

struct dyn_array { 
    int size;
    int data[];
};

struct dyn_array* my_array = malloc(sizeof(struct dyn_array) + 100 * sizeof(int));

这与将成员更改为指针的结果不同.在这种情况下,您(通常)需要两个单独的分配,一个用于结构本身,另一个用于指针指向的额外"数据.使用灵活的数组成员,您可以在单个块中分配所有数据.

This gives a different result from changing the member to a pointer. In that case, you (normally) need two separate allocations, one for the struct itself, and one for the "extra" data to be pointed to by the pointer. Using a flexible array member you can allocate all the data in a single block.

这篇关于如何在 C 中的结构中包含动态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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