gpt4 book ai didi

c - 在C中使用 token 的函数中的编译错误

转载 作者:行者123 更新时间:2023-12-02 10:53:01 24 4
gpt4 key购买 nike

我定义了一个结构并在函数中创建了该结构的初始化,但是我总是无缘无故地得到一个错误。

结构体:

typedef struct order 
{
int ident_o;
product set_prod[MAX_PRODS_OD]; /* Set of products */
int state;
}order;


功能:
order make_order(product s[])
{
order p1;
product empty_prod = {0,"",0,0,0,0};
int i = 0;
while (i<MAX_PRODS_OD)
{
s[i] = empty_prod;
i++;
}
p1 = {0,s,0}; /* creates a product and returns the created product*/
p1.ident_o = y;
/*p1.set_prod = *s; */
return p1;
}


我只能使用此命令“gcc -Wall -Wextra -Werror -ansi -pedantic”进行编译

而且我总是收到此错误:
error: expected expression before ‘{’ token
p1 = "{"0,s,0}; /* creates a product and returns the created product*/

我不明白为什么它指向这些引号之间的标记。代码正确吗?

最佳答案

初始化程序列表只能在初始化期间使用,只有在定义对象时才会出现。直接分配结构类型的每个成员的唯一方法是从与该结构类型兼容的类型的表达式中进行分配。您可以通过直接从该结构类型的另一个对象(或从该结构类型的指针的对象)进行赋值或使用复合文字来实现。这是一些代码,演示了我在说什么。

#include <stdio.h>

int main(void) {
struct foo {
int a;
int b;
};
struct foo foobar = { 0, 5}; // initialization
struct foo barbaz = { 1, 3};
struct foo *qwop;
printf("%d %d\n", foobar.a, foobar.b);

foobar = barbaz; // assigning from a struct of compatible type
printf("%d %d\n", foobar.a, foobar.b);

foobar = (struct foo){24, 99}; // assigning from compound literal
printf("%d %d\n", foobar.a, foobar.b);

qwop = &barbaz;
foobar = *qwop; // assigning from a pointer of struct of compatible type
printf("%d %d\n", foobar.a, foobar.b);
return 0;
}

从理论上讲,您也可以使用强制转换表达式,但是应该使用实际上与struct类型兼容的对象来完成此操作,否则您将面临未定义行为的风险。

关于c - 在C中使用 token 的函数中的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60922123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com