[英]Printing 2D array in a for loop crashes program
我是編程語言 C 的新手。 我正在嘗試制作一個簡單的游戲,您可以在其中四處走動並放置或刪除塊。 我正在使用終端來繪制圖形。 問題是,我希望程序打印一個X
字符后跟 24 個空白行,但是,程序直接崩潰了。 我不明白我的代碼如何或為什么會崩潰。
這是代碼:
#include <stdio.h>
int main() {
char map[79][24]; /* create the map */
int xPosition = 0, yPosition = 0; /* set the x and y position for the player */
int x, y; /* create variables for the for loop */
for (y = 0; y <= 24; y++) {
for (x = 0; x <= 79; x++) {
map[x][y] = ' ';
}
} /* initialize the map */
map[xPosition][yPosition] = 'X'; /* put the player in their position */
for (y = 0; y <= 24; y++) {
for (x = 0; x <= 79; x++) {
printf("%c", map[x][y]);
}
printf("\n");
} /* display the map on screen */
return 0;
}
你能解釋這個問題並展示正確的方法嗎? 在此先感謝 - justAnotherCoder
編輯:問題現在已解決。 謝謝您的幫助。
該程序至少具有未定義的行為,因為即使在第一個循環中也使用了初始化變量 x
int x, y; /* create variables for the for loop */
for (y = 0; x <= 24; x++) {
^^^^^^^
for (x = 0; y <= 79; y++) {
map[x][y] = ' ';
}
} /* initialize the map */
此外,循環中的條件x <= 24
和y <= 79
也是無效的。
循環沒有意義。
數組map
聲明如下
char map[79][24];
也就是說它有79
行和24
列。
所以循環應該看起來像
for (x = 0; x < 79; x++) {
for (y = 0; y < 24; y++) {
map[x][y] = ' ';
}
} /* initialize the map */
在第二對循環中應該使用相同的索引和條件。
您可以使用標准字符串 function memset
而不是初始化數組的循環
#include <string.h>
//,,,
memset( map, ' ', 79 * 24 );
這是一個演示程序(為簡單起見,我將行數從 79 減少到 24)
#include <stdio.h>
#include <string.h>
int main(void)
{
enum { M = 24, N = 24 };
char map[M][N];
memset( map, ' ', M * N );
map[0][0] = 'X';
for ( size_t i = 0; i < N + 2; i++ )
{
putchar( '-' );
}
putchar( '\n' );
for ( size_t i = 0; i < M; i++ )
{
printf( "|%.*s|\n", N, map[i] );
}
for ( size_t i = 0; i < N + 2; i++ )
{
putchar( '-' );
}
putchar( '\n' );
return 0;
}
程序 output 是
--------------------------
|X |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
--------------------------
編輯:考慮到在您更改代碼之后,如果忽略無效條件,那么您將輸出一個包含 80 列和 25 行的圖形,而不是輸出一個包含 25 列和 80 行的圖形
for (y = 0; y <= 24; y++) {
for (x = 0; x <= 79; x++) {
printf("%c", map[x][y]);
}
printf("\n");
} /* display the map on screen */
因為內部循環在一行中按順序輸出 80 個字符。
檢查您在代碼中編寫的循環條件。 為了達到預期的結果使用下面的修改代碼
#include <stdio.h>
int main() {
char map[79][24]; /* create the map */
int xPosition = 0, yPosition = 0; /* set the x and y position for the player */
int x, y; /* create variables for the for loop */
for (x = 0; x < 24; x++) {
for (y = 0; y < 79; y++) {
map[x][y] = ' ';
}
} /* initialize the map */
map[xPosition][yPosition] = 'X'; /* put the player in their position */
for (x = 0; x < 24; x++) {
for (y = 0; y < 79; y++) {
printf("%c", map[x][y]);
}
printf("\n");
} /* display the map on screen */
return 0;
}
編輯:將變量 scope 與分配的 memory 塊一起保留。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.