首页 > 解决方案 > 在 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*/

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

标签: cdata-structurescompiler-errors

解决方案


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

#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;
}

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


推荐阅读