【问题标题】:C - Struct has too many initializer valuesC - 结构有太多的初始化值
【发布时间】:2016-05-16 00:13:44
【问题描述】:

我有其他网站的代码:

typedef struct {
  byte x, y;
} Point;

typedef struct {
  Point topLeft;   /* top left point of rectangle */
  Point botRight;  /* bottom right point of rectangle */
} Rectangle;

byte rectanglesOverlap(Rectangle *Rectangle1, Rectangle *Rectangle2) {
  // If one rectangle is on left side of other
  if (Rectangle1->topLeft.x > Rectangle2->botRight.x || Rectangle2->topLeft.x > Rectangle1->botRight.x)
    return 0;

  // If one rectangle is above other
  if (Rectangle1->topLeft.y < Rectangle2->botRight.y || Rectangle2->topLeft.y < Rectangle1->botRight.y)
    return 0;

  return 1;
}

我的印象是

Rectangle *thisR = {{x, y}, {x+width, y+height}},
        *oldR = {{x2, y2}, {x2+width2, y2+height2}};

可以使用。 它编译得很好,但重叠检查总是返回 false (意思是,即使它们重叠,它也会返回好像它们从不重叠) 所以切换到 Visual Studio,我在第二点的大括号上得到了错误

{{x, y}, {
         ^

说我有“太多初始值设定项” 为什么这只是 Visual Studio 而不是 GCC 中出现的错误,它可以解释为什么重叠代码对我不起作用?几天来我一直在寻找这个问题的答案:

【问题讨论】:

  • 您正在尝试初始化一个指针。指针显然根本没有任何结构字段。我想也许您打算将 thisRoldR 声明为 Rectangle 类型,而不是指向该类型的指针。
  • 感谢您的提示,但是代码仍然无法正常工作。不过,我会检查一下 Visual Studio 是否仍然给我这个错误
  • 您的代码中可能还有其他未显示的错误。但由于您没有显示完整的代码,因此无法进一步帮助您。只能评论你展示的部分。如果您需要进一步的帮助,请显示minimal complete and verifiable example
  • 您可能正在调用其他一些期望指针作为参数的函数,但忘记将 thisRoldR 更改为 &amp;thisR&amp;oldR
  • 或者你有thisR-&gt;topLeft这样的代码,现在应该是thisR.topLeft

标签: c gcc struct rectangles initializer


【解决方案1】:

OP 正在尝试使用以下内容错误地初始化指针 @kaylum

Rectangle *thisR = {{x, y}, {x+width, y+height}},
          *oldR  = {{x2, y2}, {x2+width2, y2+height2}};

对于 C11,如果代码需要在等式或赋值的中间添加 Rectangle *,可以使用 复合文字

Rectangle *thisR = &( (Rectangle) {{x, y}, {x+width, y+height}});

怀疑这是否适用于 Visual Studio

否则使用老式的方式。

Rectangle tmpR = {{x, y}, {x+width, y+height}};
Rectangle *thisR = &tmpR;

【讨论】:

    猜你喜欢
    • 2021-01-29
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2012-07-16
    相关资源
    最近更新 更多