在C中使用变量参数全局定义数组 [英] Define array globally with variable parameter in C

查看:99
本文介绍了在C中使用变量参数全局定义数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

int EdgeCount = 0;
int numOfEdges = 0;

void addEdge() {
    // some code
    numOfEdges++;
}

int EdgeWeightArray[numOfEdges]; // error

我希望带有可变参数的全局数组在以后使用它,但是我不能这样做,因为没有 #define 我们就不能定义全局数组参数.而 #define 并不是可变的.在我的代码中, numOfEdges 是可变的,我无法使其保持不变.

I want that global array with variable parameters to use it later but I couldn't do that because without #define we can't define globally arrays parameters; and #define is not a variable thing. In my code numOfEdges is variable and I couldn't make it constant.

推荐答案

EdgeWeightArray 具有全局scobe,因此它必须为 fixed 大小.但是 numOfEdges 当然不是常量表达式.

EdgeWeightArray has global scobe, so it must be a fixed size. But numOfEdges is of course not a constant expression.

您期望 EdgeWeightArray 是什么大小?您期望在增加 numOfEdges 时它会增长吗?如果是这样,则需要查看动态内存分配.即 malloc realloc .

What size do you expect EdgeWeightArray to be? Do you expect it to grow when you increment numOfEdges? If so, you nwed to look into dynamic memory allocation; namely malloc and realloc.

没有错误检查的简要示例:

Brief example with no error checking:

int numOfEdges = 0;
int *EdgeWeightArray;
void addEdge(some parameters) {
    //SOME CODE
    numOfEdges++;
    EdgeWeightArray = realloc(EdgeWeightArray, numOfEdges * sizeof(EdgeWeightArray[0]));
}

这篇关于在C中使用变量参数全局定义数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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