为什么gcc不能一致地编译这段代码?

suh*_*ude 4 c gcc multidimensional-array

我正在为我正在参加的C编程课程做实验工作.我在我的本地Cygwin目录中编写了代码gcc,并使用它编译,并且生成的可执行文件完全按照我希望的方式工作而没有任何错误.

当我将代码复制到学校的UNIX服务器并使用它编译时gcc,我没有收到任何错误,但是当我尝试运行它时,没有任何反应.

我试过了gcc 2darray.c -Wall -pedantic,这就是返回的内容:

2darray.c: In function 'main':
2darray.c:5:3: warning: missing braces around initializer [-Wmissing-braces]
2darray.c:5:3: warning: (near initialization for 'M[0]') [-Wmissing-braces]
2darray.c:5:24: warning: C++ style comments are not allowed in ISO C90 [enabled by default]
2darray.c:5:24: warning: (this will be reported only once per input file) [enabled by default]
Run Code Online (Sandbox Code Playgroud)

这些错误提到了初始化数组的一些问题M,但我没有看到初始化它的方式有任何问题.这是我正在尝试编译的代码:

#include <stdio.h>

int main(void)
{
  int M[10][10] = {0}; // creating a 10x10 array and initializing it to 0
  int i, j; // loop variables
  int sum[10] = {0}; // creating an array to hold the sums of each column of 2d array M

  for (i = 1; i < 10; i++) // assigning values to array M as specified in directions
    {
      for (j = i - 1; j < i; j++)
        {
          M[i][j] = -i;
          M[i][j+1] = i;
          M[i][j+2] = -i;
        }
    }

  for (i = 0; i < 10; i++) // printing array M
    {
      for(j = 0; j < 10; j++)
        {
          printf("%3d", M[i][j]);
        }
      printf("\n");
    }

  printf("\n");
  for (i = 0; i < 10; i++) // calculating sum of each column
    {
      for (j = 0; j < 10; j++)
        {
          sum[i] = M[j][i] + sum[i];
        }
      printf("%3d", sum[i]);  // printing array sum
    }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我尝试在变量声明和第一个for循环和打印的语句之间插入一个printf语句,所以我的循环中可能出现问题?

如果相关,这是我的Cygwin目录中输出的内容以及我学校UNIX目录中的内容:

  0  0  0  0  0  0  0  0  0  0
 -1  1 -1  0  0  0  0  0  0  0
  0 -2  2 -2  0  0  0  0  0  0
  0  0 -3  3 -3  0  0  0  0  0
  0  0  0 -4  4 -4  0  0  0  0
  0  0  0  0 -5  5 -5  0  0  0
  0  0  0  0  0 -6  6 -6  0  0
  0  0  0  0  0  0 -7  7 -7  0
  0  0  0  0  0  0  0 -8  8 -8
  0  0  0  0  0  0  0  0 -9  9

 -1 -1 -2 -3 -4 -5 -6 -7 -8  1
Run Code Online (Sandbox Code Playgroud)

Kei*_*son 7

您正在访问M其边界外的数组行,从而导致未定义的行为.

for (i = 1; i < 10; i++) 
// i ranges from 1 to 9
  {
    for (j = i - 1; j < i; j++)
    // j ranges from i-1 (0 when i==1) to i-1 (8 when i==9)
    // Consider what happens when j==8
      {
        M[i][j] = -i;       // j == 8
        M[i][j+1] = i;      // j == 9
        M[i][j+2] = -i;     // j == 10, out of bounds
      }
  }
Run Code Online (Sandbox Code Playgroud)

当我查看你的代码时,j+2索引让我觉得最有可能进行越界访问.我复制了你的程序并添加了一行:

      M[i][j] = -i;
      M[i][j+1] = i;
      if (j+2 >= 10) puts("OUT OF RANGE");
      M[i][j+2] = -i;
Run Code Online (Sandbox Code Playgroud)

当我运行该程序时,它打印出来OUT OF RANGE.

至于你得到的警告gcc -Wall -pedantic,它们并不是真正的问题.//通过编译可以避免有关注释的警告-std=c99."缺失的大括号"警告是虚假的.嵌套数据结构的初始值设定项中的嵌套大括号是可选的,并且{0}是将整个数据结构(数组,结构,并集)初始化为零的完全有效的习惯用法.最新版本的gcc(特别是5.2.0)没有对此发出警告.