c - 为什么我的 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;
你能告诉我我提供了什么我做错了什么吗?
解决方案
问题是您Vertex
在全局空间中分配结构。不允许在全局范围内运行可执行指令,只允许在main
. 解决方法是将VtxsInLines = (struct Vertex *)(calloc(15000, sizeof(struct Vertex)));
语句移到main
函数中。您仍然可以访问分配给VtxsInLines
其他函数中变量的内存,而无需传递它,因为它VtxsInLines
是全局的。
推荐阅读
- reactjs - react js:如何在react js中从今天的日期中提取时间
- list - Groovy:比较列表忽略其中元素的顺序
- r - 如何在 rmarkdown 中使用 janitor 和 kable 垂直拆分三向表
- qt - 如何使用 QT 安装程序检测和安装先决条件?
- python - 如何使用冒泡排序按数组的长度对二维数组或多个数组进行排序
- r - 在互联网上读取 xlsx 文件
- python - 如何将excel文件的所有列读入pandas数据框中,直到满足条件?
- python - 在 django 管理命令脚本中使用多处理会产生意外错误
- azure-devops - AzureDevops REST PI:如何在测试计划下将所有测试用例和步骤导出到 excel
- react-native - 通过反应原生共享库共享视频文件抛出以下错误