定义全局变量以启动struct数组

时间:2018-05-24 15:51:52

标签: c

我正在尝试使用全局变量来存储文件中的3个值。当我运行我的项目时,这是我得到的错误:

error: variably modified ‘pkt’ at file scope
error: variably modified ‘num’ at file scope

这是我的代码:

的config.h

#ifndef READCONFIG_CONFIG_H
#define READCONFIG_CONFIG_H

#include <stdio.h>

#define PATH "src/transferConfig.txt"

extern unsigned long int TIMEOUT_PKT;
extern int START_BUFFER_SIZE;
extern float PROBLOSS;
int getConfig(){
    FILE *fp;
    int n;
    float p;
    unsigned long int t;

    if((fp = fopen(PATH,"rt")) != NULL) {
        fscanf(fp, "N=%d\n p=%f\n T=%ld\n", &n, &p, &t);
        fclose(fp);
        TIMEOUT_PKT = t;
        START_BUFFER_SIZE = n;
        PROBLOSS = p;
    }else{
        TIMEOUT_PKT = 3000000;
        START_BUFFER_SIZE = 15;
        PROBLOSS = 0;
    }
}

#endif //READCONFIG_CONFIG_H

window.h中

typedef struct window{
    packet* pkt[START_BUFFER_SIZE]; 
    long num[START_BUFFER_SIZE];
}window

构建期间出错

error: variably modified ‘pkt’ at file scope

error: variably modified ‘num’ at file scope

如何解决此错误?

1 个答案:

答案 0 :(得分:0)

START_BUFFER_SIZE在编译时是未知的,并且它不是常数,因为您可以为其分配值。可变大小的阵列需要动态内存分配。您需要在编译时知道您的数组大小才能使用静态数组。