如何在主函数外scanf全局变量?

4

我有一个问题,如何创建一个数组vertextDegree [nbColours],其中包含nbColours个元素,但"nbColours"是未知的,我必须从文件中获取它。

看一下代码,那么我应该怎么解决这个问题呢?

int nbEdges,nbVetices, nbColours ;
typedef struct st_graphVertex 
{
    int index;
    int colour;
    int val ;
    int vertexDegree[nbColours]; // it won't work because nbColours unknown     
                                 //  here and I want get it from file in the main                    
    struct st_graphVertex *next;        
    t_edgeList *out;
}t_grapheVertex;

在运行 nbColours 次的循环中执行 scanf。 - Alex F
1
http://www.c-faq.com/struct/structhack.html - jamesdlin
3个回答

2

在C99之前或非最后一个成员中,您无法这样做。相反,您可以将该成员作为固定大小指针:

int* vertexDegree;

并将其指向在运行时已知大小的适当大小的数组:
myVertex.vertexDegree = malloc(nbColours*sizeof(int));

2
在C99中,有一种特殊的语法,可以实现这个功能,尽管它仅限于每个struct只有一个数组(这在您的情况下是可以的)- 将数组作为最后一个成员,并且不需要指定其大小,像这样:
typedef struct st_graphVertex 
{
    int index;
    int colour;
    int val ;
    struct st_graphVertex *next;        
    t_edgeList *out;
    int vertexDegree[];   
}t_grapheVertex;

现在你的数组大小是灵活的:你可以在运行时决定它应该是什么。此外,不同的st_graphVertex值可以将这个大小设置得不同(尽管在这种情况下,通常会将具有特定大小的nbColours作为字段放在同一个struct中)。
使用这种技巧的“代价”是无法在堆栈或全局或静态内存中分配这样的struct。你必须像这样动态地分配它们:
t_grapheVertex *vertex = malloc(sizeof(t_grapheVertex)+sizeof(int)*nbColours);

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接