[英]Why i cant struct variable S be used to access members
我现在正在尝试学习 C,并且我有一些基本的结构问题。 我想澄清:
#define MaxSize 1024
#define ElementType int
struct DStack
{
ElementType Data[MaxSize];
int Top1; // Stack top 1
int Top2; // the top 2
} S, S2;
S.Top1 = -1;
S.Top2 = MaxSize;
编译代码时发生错误。
doubleStack.c:17:2: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
17 | S.Top1 = -1;
| ^
doubleStack.c:18:2: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
18 | S.Top2 = MaxSize;
我的编译器是gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
我编译的命令是gcc doubleStack.c -o dbs &&.\dbs
我找不到我的代码有什么问题。
在我的知识系统中,struct 可以这样使用:
struct stu{
int num;
int age;
};
// or
struct stu{
int num;
int age;
}stu1, stu2;
我希望你能帮助我找出我的错误。
提前谢谢。
您不能在 function 之外进行分配 ( s.Top1 = -1;
)。
你可以:
#define MaxSize 1024
#define ElementType int
struct DStack
{
ElementType Data[MaxSize];
int Top1; // Stack top 1
int Top2; // the top 2
} S, S2;
int main(void) {
S.Top1 = -1;
S.Top2 = MaxSize;
}
您不能有诸如S.Top1 = -1;
类的语句。 在函数之外,但您可以使用初始化程序指定在函数之外定义的变量的初始值。
对于您的示例:
#define MaxSize 1024
#define ElementType int
struct DStack
{
ElementType Data[MaxSize];
int Top1; // Stack top 1
int Top2; // the top 2
};
struct DStack S = {
.Top1 = -1,
.Top2 = MaxSize
};
struct DStack S2;
上面的S
初始化使用指定的初始化语法,允许为单个成员或数组元素指定初始值。 未指定的成员和数组元素将被初始化为 0。
自 1999 版 C 标准以来,指定初始化程序一直是标准功能,但一些较旧的编译器不支持它们。 如果不支持指定的初始化器,则可以使用旧形式的初始化器语法初始化S
,如下所示:
struct DStack S = {
{0}, /* Data[] */
-1, /* Top1 */
MaxSize /* Top2 */
};
使用较旧的语法,初始化程序中的值用于按照它们在struct
中声明的相同顺序来初始化成员,或者用于初始化从索引 0 开始的数组元素。 初始化器中的嵌套{
}
可用于初始化包含在另一个 object 中的复合对象,就像初始化上面的Data
数组成员一样。 如果不使用嵌套的{
}
,则需要有 1024 个Data
初始值,然后是Top1
和Top2
的初始值。 上面使用{0}
指定Data[0]
显式初始化为 0,而Data
的其余元素( [1]
到[1023]
)将隐式初始化为默认值 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.