首页 > 解决方案 > 为什么我的 C 结构声明不被识别?

问题描述

我正在开发一个 TIN 模型应用程序,并且我在 C 程序顶部的公共区域中定义了一个结构“顶点”。

struct Vertex
{
    int GblSeqNum;
    int PlySeqNum;
    struct Polyline *Line;
    double CtrZ;
    double x;
    double y; 
    double z;
    struct Edge *OwnerEdge;
    struct Vertex *NextVtx;
    struct Vertex *PrevVtx;
};

接下来,在 Vertex 结构的正下方,我声明了一个指向 Vertex 结构的全局指针:

struct Vertex *VtxsInLines;

然后,仍然在公共区域,我使用 calloc 为我的顶点分配空间:

VtxsInLines = (struct Vertex *)(calloc(15000, sizeof(struct Vertex)));

我在 Windows 10 上使用 MinGW 使用 GNU C 编译器编译代码:

C:\000WORKIndexedTasks 000-999\500 Papers\523 PositionalAccuracyContourLines>gcc -c 523*.c

会生成以下警告和错误:

523Paper_ReadContourVertices.c:98:1: warning: data definition has no type or storage class
 VtxsInLines = (struct Vertex *)(calloc(15000, sizeof(struct Vertex)));
 ^~~~~~~~~~~
523Paper_ReadContourVertices.c:98:1: warning: type defaults to 'int' in declaration of 'VtxsInLines' [-Wimplicit-int]
523Paper_ReadContourVertices.c:98:1: error: conflicting types for 'VtxsInLines'
523Paper_ReadContourVertices.c:47:16: note: previous declaration of 'VtxsInLines' was here

    struct Vertex *VtxsInLines;
                  ^~~~~~~~~~~
523Paper_ReadContourVertices.c:98:15: warning: initialization of 'int' from 'struct Vertex *' makes integer from pointer without a cast [-Wint-conversion]
 VtxsInLines = (struct Vertex *)(calloc(15000, sizeof(struct Vertex)));

看来我的声明在某种程度上是错误的,这导致编译器假定为 int 类型。这会在以后产生很多错误,例如:

523Paper_ReadContourVertices.c: In function 'main':

523Paper_ReadContourVertices.c:432:20: error: invalid type argument of '->' (have 'int')
   

    (VtxsInLines+idx)->GblSeqNum = -1;

你能告诉我我提供了什么我做错了什么吗?

标签: cpointersgnucalloc

解决方案


问题是您Vertex在全局空间中分配结构。不允许在全局范围内运行可执行指令,只允许在main. 解决方法是将VtxsInLines = (struct Vertex *)(calloc(15000, sizeof(struct Vertex)));语句移到main函数中。您仍然可以访问分配给VtxsInLines其他函数中变量的内存,而无需传递它,因为它VtxsInLines是全局的。


推荐阅读