use*_*491 19 c arrays loops abort
我有这个代码:
void drawInitialNim(int num1, int num2, int num3)
{
int board[2][50]; //make an array with 3 columns
int i; // i, j, k are loop counters
int j;
int k;
for(i=0;i<num1+1;i++) //fill the array with rocks, or 'O'
board[0][i] = 'O'; //for example, if num1 is 5, fill the first row with 5 rocks
for (i=0; i<num2+1; i++)
board[1][i] = 'O';
for (i=0; i<num3+1; i++)
board[2][i] = 'O';
for (j=0; j<2;j++) { //print the array
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
}
return;
}
int main()
{
int numRock1,numRock2,numRock3;
numRock1 = 0;
numRock2 = 0;
numRock3 = 0;
printf("Welcome to Nim!\n");
printf("Enter the number of rocks in each row: ");
scanf("%d %d %d", &numRock1, &numRock2, &numRock3);
drawInitialNim(numRock1, numRock2, numRock3); //call the function
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我使用gcc编译它时,它很好.当我运行该文件时,输入值后我得到了中止陷阱6错误.
我查看了有关此错误的其他帖子,他们没有帮助我.
ryy*_*ker 29
你写的是你不拥有的记忆:
int board[2][50]; //make an array with 3 columns (wrong)
//(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
board[2][i] = 'O';
^
Run Code Online (Sandbox Code Playgroud)
改变这一行:
int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
^
Run Code Online (Sandbox Code Playgroud)
至:
int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
^
Run Code Online (Sandbox Code Playgroud)
创建数组时,用于初始化的值[3]表示数组大小.
访问现有数组时,索引值基于零.
对于创建的数组: int board[3][50];
法律索引是董事会[0] [0] ...董事会[2] [49]
编辑 解决错误的输出注释和初始化注释
为格式化输出添加额外的"\n":
更改:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
}
...
Run Code Online (Sandbox Code Playgroud)
至:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
printf("\n");//at the end of every row, print a new line
}
...
Run Code Online (Sandbox Code Playgroud)
初始化板变量:
int board[3][50] = {0};//initialize all elements to zero
Run Code Online (Sandbox Code Playgroud)
尝试这个:
void drawInitialNim(int num1, int num2, int num3){
int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function.
int i, j, k;
for(i=0; i<num1; i++)
board[0][i] = 'O';
for(i=0; i<num2; i++)
board[1][i] = 'O';
for(i=0; i<num3; i++)
board[2][i] = 'O';
for (j=0; j<3;j++) {
for (k=0; k<50; k++) {
if(board[j][k] != 0)
printf("%c", board[j][k]);
}
printf("\n");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
103345 次 |
| 最近记录: |