【问题标题】:C lang array length variable got changedC语言数组长度变量get改变
【发布时间】:2022-11-27 00:13:12
【问题描述】:

我试图找出为什么 positiveNum 被更改。我找到了它被改变的地方,但不知道为什么会这样。

#include <stdio.h>

typedef struct TernaryGroup {
  int size;
  int groupList[][3];
} TernaryGroup;

int test(int num) {
  int positiveNum = num + 1;
  TernaryGroup ternaryGroups[positiveNum];
  for (int index = 0; index < positiveNum; index++) {
    ternaryGroups[index].size = 0;
  }
  for (int aIndex = 1; aIndex < positiveNum; aIndex++) {
    for (int bIndex = aIndex + 1; bIndex < positiveNum; bIndex++) {
      for (int cIndex = bIndex + 1; cIndex < positiveNum; cIndex++) {
        int isUnsafeTernary = (2 * (bIndex - aIndex)) == (cIndex - bIndex);
        if (!isUnsafeTernary) {
          continue;
        }
        int newTernary[3] = {aIndex, bIndex, cIndex};

        for (int index = 0; index < 3; index++) {
          int groupName = newTernary[index];
          int curGroupSize = ternaryGroups[groupName].size;
          // positiveNum is changed by these lines, but I don't know why
          ternaryGroups[groupName].groupList[curGroupSize][0] = aIndex;
          ternaryGroups[groupName].groupList[curGroupSize][1] = bIndex;
          ternaryGroups[groupName].groupList[curGroupSize][2] = cIndex;

          ternaryGroups[groupName].size++;
        }
        printf("newTernary %d %d %d\n", aIndex, bIndex, cIndex);
        printf("why positiveNum %d is not 7 \n", positiveNum);
      }
    }
  }

  return num;
}
int main() {
  test(6);
  return 0;
}

【问题讨论】:

    标签: c gcc


    【解决方案1】:

    TernaryGroup 结构以灵活的数组成员 int groupList[][3]; 结尾。没有为该成员保留空间,并且永远不应在数组中使用该结构。

    TernaryGroup ternaryGroups[positiveNum];定义了一个ternaryGroups的数组。如果您的编译器没有发出关于此的警告,请在您的编译器中启用警告并将警告提升为错误。对于 Clang,以 -Wmost -Werror 开头。对于 GCC,以 -Wall -Werror 开头。对于 MSVC,以 /W3 /WX 开头。

    当后面的代码尝试使用此数组中元素的 groupList 成员时,它们会尝试访问数组的未定义元素。

    您不能使用此结构以您想要的方式保存数据。您必须重新设计程序以使用单独分配的 TernaryGroup 结构,每个结构为其灵活数组成员分配所需的空间,或者您必须重新设计结构以使 groupList 成员不是灵活数组成员。它可以是指向别处内存的指针,您必须类似地分配内存。

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 2016-07-29
      • 1970-01-01
      • 2012-03-01
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      相关资源
      最近更新 更多