【问题标题】:Why can't I assign a struct variable an element of an array of the same type of structs?为什么我不能为结构变量分配相同类型结构的数组的元素?
【发布时间】:2021-09-25 14:25:44
【问题描述】:

我尝试使用 = 运算符从相同类型结构的数组中分配结构变量值,如下所示:

struct s {
    int dummy;
    char somechar[8];
} array_of_s[10];

void f(void)
{
    struct s a = array_of_s[0];  // this line gives me error message
}

int main(void)
{
    f();
    return 0;
}

我收到一条错误消息,上面写着:

a value of type "struct s" cannot be used to initialize an entity of type "struct s"C/C++(144)

但如果我像下面这样将数组作为参数传递,它就像一个魅力:

struct s {
    int dummy;
    char somechar[8];
} array_of_s[10];

void f(struct s array_as_parameter[])
{
    struct s a = array_as_parameter[0];
}

int main(void)
{
    f(array_of_s);
    return 0;
}

为什么第一个代码是非法的?我不应该能够访问外部数组变量并分配它吗?

【问题讨论】:

  • 尝试使用赋值而不是初始化。

标签: arrays c variables struct


【解决方案1】:

我不明白。

gcc -Wall -Wextra -o main main.c 编译得很好。

#include <stdio.h>

struct s {
    int dummy;
    char somechar[8];
} array_of_s[10] = {{123, "abc"}};

void f(void)
{
    struct s a = array_of_s[0];
    printf("%d, %s\n", a.dummy, a.somechar);
}

int main(void)
{
    f();
    return 0;
}

输出:

123, abc

另一方面,VSCode 也向我显示了该错误消息。

这是一个错误,看看这个:https://github.com/microsoft/vscode-cpptools/issues/3212

【讨论】:

  • @Clifford 我必须道歉,我误解了你的评论。你从一开始就是对的。我不知道,我读过什么,我对你的评论的回答不是很好。
  • 不需要。我假设“我不明白”你的意思是你没有得到错误,而不是“我不明白”这就是我的意思先读一读。
  • 我查看了代码,没有发现任何错误。我已经在我的系统上对其进行了测试,它按预期运行。 “我不明白”的意思是:我在这里没有看到任何问题,它一定是不同的东西。区别在于您在对我的回答的第一条评论中提到的内容(但已将其删除)。
  • 如你所说,它看起来像a bug in VS,纯粹而简单。
  • OP 应该注意到您发布的链接在github.com/microsoft/vscode-cpptools 有一个解决方案,但忽略该消息并相信编译器可能更容易。
【解决方案2】:

线索在错误消息中 - 你没有分配你正在初始化

改为:

struct s a ;
a = array_of_s[0]; 

也就是说,我从未见过这样的错误消息(最后是 C/C++(144) - 它们是两种不同的语言 - 这没什么意义)。此外,它在 GCC 中编译得很好——你使用的是什么编译器(和版本)?这实际上不是编译器诊断,而是您的 IDE/编辑器执行的预解析?

【讨论】:

  • 我必须道歉,我误解了你的评论。你从一开始就是对的。我不知道,我读过什么,我对你的评论的回答不是很好。
  • 看起来错误消息“C/C++”来自 Microsoft 产品,而且与您和我不同,Microsoft确实倾向于认为“C/C++”是一种语言。根据与@ErdalKüçük 的回答相关的讨论,看起来这 is 是由 IDE 执行的预解析,并且是错误的。
  • @SteveSummit 就像 Clifford 在上面对我的回答的评论中提到的那样,存在针对该特定错误消息的解决方法。
猜你喜欢
  • 2012-12-05
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 2012-08-24
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
  • 2010-10-19
相关资源
最近更新 更多