gpt4 book ai didi

c - 语法错误: '{'

转载 作者:行者123 更新时间:2023-11-30 18:16:42 25 4
gpt4 key购买 nike

我正在编写一个使用整数数组的 C 程序,该数组是结构的一部分。其结构为:

struct test
{
int *ques;
int a;
int b;
int len; // len is the length of the array defined in the structure as ques.

};

在此声明之后的函数中,我为 len 分配了一个值:

cases[0].len=5; // here cases is an array of the type struct test.

然后我使用 malloc 为数组成员 ques 分配内存,如下所示:

cases[0].ques=(int *)malloc(cases[counter].len*sizeof(int));

之后,我尝试按如下方式填充数组ques:

cases[0].ques[5]={-7,-6,-5,-4,-3};

在编译时,我在上面的行中收到一个错误,指出:

maxmin.c(47) : error C2059: syntax error : '{'

你能帮我一下吗?

最佳答案

这是无效的:cases[0].ques[5]={-7,-6,-5,-4,-3};

在 C 语言中,您可以通过这种方式初始化数组,但只能在声明数组时进行。

要在 C 程序中填充此时的值,您应该使用 for 循环分别填充每个索引。

现在 C 编译器将此语句解析为:

类型为 的结构体数组 cases 的索引 0 处的数组 ques 的索引 5 的值struct test{-7,-6,-5,-4,-3},这肯定是无效的,因为在分配 a 时不能使用 {变量值。

OP评论更新:

您可以保留临时数组中的所有值,例如int temp[50] = {...};,然后在为ques分配空间后您可以使用memcpy 函数将 len 个值复制到 ques

关于c - 语法错误: '{' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22980389/

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