问题
I have a 2d array (a chess board, but this is irrelevant to the problem) and I want to fill it using a function. The one I've written works fine, but after launching the program the console crashes. Any idea where the problem is? Thank you.
#include <stdio.h>
#include <stdlib.h>
void fill(int board[8][8]);
int main()
{ int board[8][8];
fill(board);
return 0;
}
void fill(int board[8][8])
{
int a,b;
for (a = 1; a <= 8; a++)
{
for (b = 1; b<= 8; b++)
{
if ((a==1) || (a==8)) board[a][b] = 7;
if ((a==2) || (a==7)) board[a][b] = 9;
if ((a==3) || (a==6)) board[a][b] = 11;
if ((a==4) || (a==5)) board[a][b] = 13;
printf("%d", board[a][b]);
}
printf("\n");
}
}
回答1:
I see one problem: arrays are indexed from 0 in C. So the last case is board[7][7].
Accessing board[8][0] actually accesses the sub-array (the row) after the end of the actual array. It will compile but crash if the memory after the array isn't owned by your program (the famous segmentation fault).
I guess you should put a-1 and b-1 between the square brackets.
回答2:
Because you have access array out of bound. Array index start to zero in c.
回答3:
In your for-loop conditions:
for (b = 1; b<= 8; b++)
and
for (a = 1; a <= 8; a++)
Your for-loop runs till counter a and b is equal to 8. However, your array itself is deeclared as board[[8][8] which means that the counters for both the arrays should be from 0 to 7. Since your counter exceeds the last value of the array, it causes undefined behaviour, and leads to a segmentation fault.
You need to change your for-loop condition to:
for (b = 0; b < 8; b++)
and
for (a = 0; a < 8; a++)
EDIT: Judging from the rest of your code in the for-loop, changing the conditional statement of these loops will change the logic of your program. In that case, you could instead use board[a -1][b - 1] at all instances instead of board[a][b].
Using this method, the counter will only reach 8 - 1 = 7 for both counter cases, and will avoid a segmentation fault just like the first solution.
回答4:
As noted in several comments/answers, array index values range from 0 to n-1,
Change the following lines:
for (a = 1; a <= 8; a++)
{
for (b = 1; b<= 8; b++)
To:
for (a = 0; a <= 7; a++)
{
for (b = 0; b<= 7; b++)
Follow this with adjustments to the comparison statements in the inner loop accordingly.
来源:https://stackoverflow.com/questions/43018001/passing-a-2d-array-to-function-in-c