【发布时间】:2021-05-01 01:35:24
【问题描述】:
我是 C 编程新手,所以我开始制作一个简单的项目。我对以下代码有疑问,这似乎与在 C 中管理内存的方式有关,但我不确定。
我有一个 1280x720 的粒子数组,我用零和“无”填充。然后我在 (1,1) 处填写一个条目。最后我打印出所有不是“无”的“粒子”。奇怪的行为来自这样一个事实,当我这样做时,我得到了以下输出:
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);
}
}
}
}
抱歉,这是一个简单的问题。提前致谢。
【问题讨论】:
标签: c object memory-management