在创建可变变量后,标量初始化器中存在多余的元素。

huangapple go评论49阅读模式
英文:

Excess elements in scalar initializer after make an mutable variable

问题

我在尝试初始化数据以便在需要更改数据时进行更改时遇到错误“标量初始化器中的多余元素”。因为之前我的数据只是定义而已,但当我进行初始化时,错误就出现了。我不太理解这个错误。有人可以解释并给我一个如何使其工作的示例吗?

int box[15][2] = {{0}};
if (hand == "right"){
    int newBox[15][2] = {{45,85}, {45, 75}, {45, 65}, {65, 85}, {65, 75}, {65, 65}, {25, 85}, {25, 75},
                           {25, 65}, {5, 85}, {5, 75}, {5, 65}, {85, 85}, {85, 75}, {85, 65}};
    // 使用新的数据进行操作
}
英文:

I get the error "Excess elements in scalar initializer" when I try to make init data so I can change the data when it need to me changed because before my data just define. But when I make an init then the error shows up. I don't really understand the error. Can anyone explain and give me an example of how to make it work?

int box[15][2] = {{0}};
    if (hand == "right"){
        box[15][2] = {{45,85}, {45, 75}, {45, 65}, {65, 85}, {65, 75}, {65, 65}, {25, 85}, {25, 75},
                           {25, 65}, {5, 85}, {5, 75}, {5, 65}, {85, 85}, {85, 75}, {85, 65}};
    }

答案1

得分: 0

  1. 你只能在声明数组时使用初始化列表来设置数组。无法将这样的列表分配给已经声明的数组。
  2. box[15][2] 不是对 box 的有效引用(最后一个元素是 box[14][1])。
  3. hand == "right" 没有意义。你正在比较一个(希望是)char 指针与指向常量字符串 "right" 的指针。即使 hand 已经设置为该常量字符串,也不能保证在比较中使用相同的指针。看起来你想比较 hand 处的字符串与 "right",但这并不实现。

要设置数组 box,一种方法是创建另一个包含所需内容的常量数组,然后使用 memcpy() 将其复制到 box 中。

要比较两个字符串,请使用 strcmp()

英文:
  1. You can only use an initializer list to set an array when the array is declared. You cannot assign such a list to an already declared array.
  2. box[15][2] is not a valid reference to box. (The last element is box[14][1].)
  3. hand == "right" makes no sense. You are comparing what is (hopefully) a char pointer to a pointer to the constant string "right". Even if hand had been set to that constant string, there is no guarantee that the same pointer would be used in the comparison. It looks like you want to compare the string at hand to "right", which that doesn't do.

To set the array box, one way would be to make another constant array with what you want, and then using memcpy() to copy that over box.

To compare two strings, use strcmp().

huangapple
  • 本文由 发表于 2023年6月19日 10:44:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76503324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定