问题
I want to initialize a 5x5 array with 0 as content of each array index. But whenever i run my code, i get segmentation fault(core dumped error). Can you please help me what is the problem with my code. My code is as follows.
#include <stdio.h>
int main()
{
int a[5][5];
int i,j;
for(i=0; i<=5; i++)
{
for(j=0; j<=5; j++)
{
a[i][j]=0;
}
}
}
回答1:
You have an array of 5 rows (indexed 0..4) and 5 cols (indexed 0..4), but you are accessing 6 rows (indexes 0..5) and 6 cols (indexes 0..5). You need to adjust the bounds on your loop.
#define ROWS 5
#define COLS 5
int a[ROWS][COLS];
for (int i=0; i<ROWS; ++i) {
for (int j=0; j<COLS; ++j) {
a[i][j] = 0;
}
}
That said, you could simply use the following to initialize the array:
#define ROWS 5
#define COLS 5
int a[ROWS][COLS] = { 0 };
Note that I used names rather than hardcoding the numbers everywhere. This is far more readable and far less error-prone.
回答2:
For arrays in C, indexing starts from 0.
When we declare an array a[5]
, which obviously indicates that we are allocating 5
memory space of some data types for a
, one way to access those memory address is to use the indexes. As I have stated earlier that in C, indexing starts from 0, those 5 space would be:
1 2 3 4 5 <--------- Actual position
a[0] a[1] a[2] a[3] a[4] <--------- Array index
So, when we will try to access a[5]
for above example, that will lead to segmentation fault.
Similarly, for your case, you should correct your for-loop like below:
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
a[i][j] = 0;
}
}
回答3:
The problem is <=
insted of <
It will do the loop 6 times ,and set 0 in each a[i][j]
in the 2d array
It will start from a[0][0]
to a[5][5]
but u gave hem a memory of 5 cubes(0,1,2,3,4 its start from 0 , not 1) , and the loop set 6 cubes(0,1,2,3,4,5) but 5 is not in the array , so u have a segmentation fault.
回答4:
Your mistake:
for(i=0; i<=5; i++) // accessed extra element where there are only 5 (i < 5)
for(j=0; j<=5; j++) // same with this, correct: (j < 5)
a[i][j]=0;
Correct solution is:
for(i = 0; i < 5; i++)
for(j = 0; j < 5; j++)
a[i][j]=0;
Use:
int a[5][5] = {0};
to initialize multidimensional arrays to zero.
More concepts could be found in this thread.
来源:https://stackoverflow.com/questions/61757325/why-my-code-give-segmentation-faultcore-dumped-error