c - C 新手...结构找不到我确定的变量

标签 c struct

我是整个 C 语言的新手,但我的代码一直出现这个错误

UArray2.c:19:error: request for member ‘i’ in something not a structure or union

这显然是我的主要功能中的 uarray.i,但我不明白为什么它没有看到它。

这是我的 .h 文件。不太有趣...

//UArray2.h
#include <stdlib.h>
#include <stdio.h>
#ifndef UARRAY2_INCLUDED
#define UARRAY2_INCLUDED
#define T UArray2_T
typedef struct T *T;

#undef T
//#undef UARRAY2_INCLUDED //undef?                 
#endif

这是我的.c 文件。非常简单的东西。

//UArray.c                                              
#include <stdlib.h>
#include <stdio.h>
#include "UArray2.h"
#define T UArray2_T

struct T{
     int i;
};

int main()
{
     UArray2_T uarray;
     uarray.i=0;
     return 0;
}
#undef T

那么,有人知道为什么我会收到此编译错误吗?这可能是我做的蠢事。

最佳答案

在你的头文件中

typedef struct T *T;

这意味着当您声明变量 uarray 时,您实际上是在声明一个指针。所以你应该将 i 成员初始化为

uarray->i = 0;

然而,这很可能会崩溃,因为指针未初始化并且可以指向内存中的任何位置。要么为指针分配内存

UArray2_T uarray = malloc(sizeof(*uarray));

或者让它指向另一个结构

struct UArray2_T real_uarray;
UArray2_T uarray = &real_uarray;

关于c - C 新手...结构找不到我确定的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12471135/

相关文章:

c - 创建 AST 后进行语义检查

C程序可以编译成DLL吗

c - C 运算符的优先级

c - 警告 : return makes pointer from integer without a cast using malloc sizeof struct in C

c - C 或 D 的具有浮点语义的整数类型

c# - C# 中的结构指针初始化

swift - 知道变量是类还是结构的实例

c - 下标值既不是数组也不是指针

java - 是否有特定的方法来处理 JNA 中结构的 const 指针成员?

c++ - 编译器降低程序的时间复杂度是否合法?这被认为是可观察的行为吗?