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

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

问题描述

我环顾四周,但一直未能找到解决什么必须是一个好问的问题。
这里是code我有:

 的#include<&stdlib.h中GT;结构my_struct {
    INT N;
    个char []
};诠释的main()
{
    结构my_struct毫秒;
    ms.s =的malloc(sizeof的(字符*)* 50);
}

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

我可以得到它来编译,如果我宣布结构内S的声明为

 的char * S

这可能是一个卓越的实现(指针运算比数组快,是吗?)
但我认为在C的声明

 个char []

是相同的

 的char * S


解决方案

您现在写的,曾经被称为结构黑客,直到C99祝福它作为一种柔性数组成员的方式。你得到一个错误(可能是这样)的原因是,它需要跟一个分号:

 的#include<&stdlib.h中GT;结构my_struct {
    INT N;
    个char [];
};

当你为这个分配空间,要分配的大小结构的以及的要用于阵列的空间量:

 结构my_struct * S =的malloc(sizeof的(结构my_struct)+ 50);

在此情况下,柔性数组成员是char类型的数组,和sizeof(char)的== 1,这样你就不会需要通过其规模倍增,但就像任何其他的malloc你需要,如果这是一些其他类型的数组:

 结构dyn_array {
    INT大小;
    int数据[];
};结构dyn_array my_array =的malloc(sizeof的(结构dyn_array)+ 100 * sizeof的(INT));

编辑:这给出了从该构件改变到指针不同的结果。在这种情况下,(通常)需要两个单独的分配,一个用于结构本身,和一个用于额外的数据要由指针指向。使用灵活的数组成员可以分配在一个块中的所有数据。

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);
}

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

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

char* s

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

char s[]

is the same as

char* s

解决方案

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);

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));

Edit: 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天全站免登陆