简体   繁体   English

编译器错误:C结构中的“预期;”错误

[英]compiler error: “Expected ;” error in C struct

I'm trying to add a struct to my program using this syntax: 我正在尝试使用以下语法将struct添加到程序中:

struct foo {
    char bar[] = "baz";
    char qux[] = "abc";
    /* and so on */
};

For some reason, I get an error on each variable declaration within the struct saying that I have to add semicolons, and seems to fall into a kind of loop with this. 由于某种原因,我在struct每个变量声明上都出错,说必须添加分号,并且似乎陷入了这种循环。 The suggested syntax would be something like 建议的语法将类似于

struct foo {
    char bar[]; =; ;;;;;;/* infinite semicolons */"baz";
}

This is the first time I've had this kind of error; 这是我第一次遇到这种错误。 am I really doing something wrong, or is this just an issue with the compiler itself? 我是不是真的做错了,还是编译器本身有问题?

This has nothing to do with Xcode. 这与Xcode无关。 At all. 完全没有

You're getting a compiler error because you can't initialize structs like this. 您会收到编译器错误,因为您无法初始化这样的结构。

The struct type definition is about types only. 结构类型定义仅关于类型。 Assigning values to members at this point makes no sense. 此时,为成员分配值没有任何意义。 Maybe you meant 也许你是说

struct foo {
    char *bar;
    char *baz;
};

struct foo x = { "quirk", "foobar" };

instead? 代替?

You are doing something wrong. 您做错了。 You cannot assign values to the members of the struct… you're in the middle of defining the data type, not an instance of it. 您不能将值分配给该结构的成员……您正在定义数据类型,而不是它的实例。

This will give you your struct definition and then directly declare a variable (with initialization) of its type: 这将为您提供结构定义,然后直接声明其类型的变量(带有初始化):

struct foo {
    char *bar;
    char *qux;
} variable_name = {
    "baz", "abc"
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM