给出奇怪行为的 C 结构数组

C array of structs giving strange behaviour

我是 C 语言编程的新手,所以我开始制作一个简单的项目。我在使用以下代码时遇到问题,这似乎与 C 中的内存管理方式有关,但我不确定。 我有一个 1280x720 的粒子数组,我用零和“none”填充它。然后我在 (1,1) 处填写一个条目。最后我打印出所有不是“none”的'particles'。奇怪的行为来自这样一个事实,即当我这样做时,我得到以下输出: 721 0 sand 1 1 sand 显然第二个值应该存在,但第一个不应该存在。我尝试过使用不同的 x,y 值,它总是将 720 添加到 x,并从 y 中减去 1。

#include <stdio.h>
#include <string.h>

typedef struct {
  char name[10];
  int colour;
} Particle;

Particle particles[1280][720];

void main() {
  //Fill in the 1280 x 720 array with 0's and None
  for (int y=0; y<720; y++) {
    for (int x=0; x<1280; x++) {
      particles[y][x].colour = 0x000000;
      strcpy(particles[y][x].name, "none");
    }
  }

  //Copy in 1 pixel of sand
  strcpy(particles[1][1].name, "sand");
  particles[1][1].colour = 0xFFFF00;

  //Print out all the pixels that are not none, which should
  //just print out a single pixel at (1,1)
  for (int y=0; y<720; y++) {
    for (int x=0; x<1280; x++) {
      if (strcmp("none",particles[y][x].name) != 0) {
        printf("%d %d %s\n",x,y,particles[y][x].name);
      }
    }
  }
}

抱歉,如果这是一个简单的问题。提前致谢。

数组particles的每一行只有720个元素,所以particles[y][x]x >= 720时超出范围。访问超出范围的元素会调用 未定义的行为

引自N1570 J.2 未定义行为:

An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).

分配足够的元素以避免缓冲区溢出。看来你应该使用

Particle particles[720][1280];

而不是

Particle particles[1280][720];

宽度和高度最好用宏来定义,以免打错:

#include <stdio.h>
#include <string.h>

#define WIDTH 1280
#define HEIGHT 720

typedef struct {
  char name[10];
  int colour;
} Particle;

Particle particles[HEIGHT][WIDTH];

void main() {
  //Fill in the WIDTH x HEIGHT array with 0's and None
  for (int y=0; y<HEIGHT; y++) {
    for (int x=0; x<WIDTH; x++) {
      particles[y][x].colour = 0x000000;
      strcpy(particles[y][x].name, "none");
    }
  }

  //Copy in 1 pixel of sand
  strcpy(particles[1][1].name, "sand");
  particles[1][1].colour = 0xFFFF00;

  //Print out all the pixels that are not none, which should
  //just print out a single pixel at (1,1)
  for (int y=0; y<HEIGHT; y++) {
    for (int x=0; x<WIDTH; x++) {
      if (strcmp("none",particles[y][x].name) != 0) {
        printf("%d %d %s\n",x,y,particles[y][x].name);
      }
    }
  }
}