文件范围内的可变长度数组? [英] Variable-length array in file scope?

查看:39
本文介绍了文件范围内的可变长度数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有这个代码.

#include <stdlib.h>
#include <stdio.h>
#define array_size 3

typedef struct {
    int array[array_size];
} TEST;

void printout(TEST *p, int element) {
    printf("element: %i\n", p->array[element]);
}

int main(void) {
    TEST *p;
    p = malloc(sizeof(TEST));
    p->array[0] = 5;
    printout(p, 0);

    return 0;
} 

但我想根据用户输入分配 "array_size" .

But I'd like to assign "array_size" based on user input.

如果我尝试这样做,编译器会说在文件范围内可变地修改了‘array_size’".那么,我做我想做的唯一方法是将所有内容移动到 main().. 吗?

If I try to do so, the compiler says "variably modified ‘array_size’ at file scope". So, am I right that the only way to do what I want is to move everything to main()..?

它工作得很好,但是将结构和函数声明保持在文件范围内似乎很整洁.

It works just fine, but keeping structs and functions declarations in file scope seems, you know, neat.

推荐答案

最简单的方法就是动态分配内存:

The simplest approach is to just allocate the memory dynamically:

typedef struct {
    int *array;
    size_t size;
} TEST;

int main() {
    size_t elem_count = /* from user input */
    TEST p;
    p->array = malloc(elem_count * sizeof int);
    if(!p->array)
        return -1;

    p->size = elem_count;
    /* ... */
    free(p->array);
}

这篇关于文件范围内的可变长度数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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