c - 在 C 中使用标记的函数编译错误
问题描述
我定义了一个结构并在函数中创建了该结构的初始化,但我总是无缘无故地出错。
结构:
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;
}
从理论上讲,您也可以使用强制转换表达式,但这应该使用与结构类型实际上兼容的对象来完成,否则您将面临未定义行为的风险。
推荐阅读
- javascript - 如何避免必须对具有 2 个条件的 javascript 数组进行两次排序
- javascript - 似乎无法访问反应导航中的参数
- sql - 计算闰年月份的天数
- java - java中如何强制子类实现其非抽象、非接口实现的父类的方法?
- python-3.x - 基于月份和日期的多个 pandas 数据帧的叠加图
- javascript - MVC - 我的表单没有通过我的选择下拉列表的选择选项
- xml - 将 XML 导入 MS Access - Chrome 身份验证问题
- swift - SwiftUI:Image 和 UIImage 有什么区别?
- pandas - 无法使用替换来更新数据框标题
- docker - 如何从 Kubernetes 中的容器连接到外部世界