用户定义类型在C动态大小 [英] User defined types with dynamic size in C

查看:169
本文介绍了用户定义类型在C动态大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欲限定组成与由用户输入的大小的阵列的新的数据类型。例如,如果用户输入128,则我的节目应该使一个新的类型,它基本上是16个字节的阵列。这种结构的定义必须是全球性的,因为我要在我的程序之后使用该类型。有必要对这种结构的动力大小,因为我将具有由该类型的最终变量填充一个庞大的数据库。

I want to define a new data type consisting of an array with a size inputted by the user. For example if the user inputs 128, then my program should make a new type which is basically an array of 16 bytes. This structure's definition needs to be global since I am going to use that type thereafter in my program. It is necessary to have a dynamic size for this structure because I will have a HUGE database populated by that type of variables in the end.

在code我现在是:

struct user_defined_integer;
.
.
.
void def_type(int num_bits)
{
    extern struct user_defined_integer 
    {
             int val[num_bits/sizeof(int)];
    };

return;

}

(这是不工作)

最接近我的问题,我发现,在这里:
<一href=\"http://stackoverflow.com/questions/9830507/i-need-to-make-a-global-array-in-c-with-a-size-inputted-by-the-user\">I需要进行一个全局数组用C与由用户的输入的大小
(是不是有用)

The closest thing to my question, I have found, is in here: I need to make a global array in C with a size inputted by the user (Which is not helpful)

有没有办法做到这一点,让自己的结构是在整个文件认可?

Is there a way to do this, so that my structure is recognized in the whole file?

推荐答案

做当:

extern struct user_defined_integer 
{
         int val[num_bits/sizeof(int)];
};

您应该得到警告:

warning: useless storage class specifier in empty declaration 

因为你有一个空的声明。 的extern 不适用 user_defined_integer ,而在的它自带变量的。其次,这无论如何也不会因为包含一个可变长度数组结构不能有任何的联系工作。

because you have an empty declaration. extern does not apply to user_defined_integer, but rather the variable that comes after it. Secondly, this won't work anyway because a struct that contains a variable length array can't have any linkage.

error: object with variably modified type must have no linkage

但即便如此,变长数组在声明的点分配存储空间。您应该选择的动态内存。

Even so, variable length arrays allocate storage at the point of declaration. You should instead opt for dynamic memory.

#include <stdlib.h>

typedef struct
{
    int num_bits;
    int* val;
} user_defined_integer;

void set_val(user_defined_integer* udi, int num_bits)
{
    udi->num_bits = num_bits;
    udi->val = malloc(num_bits/sizeof(int));
}

这篇关于用户定义类型在C动态大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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