Segmentation fault when accessing an array through a pointer
I have a global array declared as
int Team1[12][8];
When I call the function
int readLineupB(int teamNr){
int (*teamToRead)[12][8];
teamToRead = &Team1;
for (int currentPlayersNumber = 1; currentPlayersNumber<11; currentPlayersNumber++) {
for (int otherNumber = 1; otherNumber<7; otherNumber++) {
*teamToRead[currentPlayersNumber][otherNumber] = 20;
}
}
return 1;
}
it fills the array up to position [10], [3] and then apparently for [10], [4] I get a segmentation fault and I can't figure out why.
source to share
Check data types.
teamToRead
is a pointer to an array int [12][8]
.
Due to operator precedence , the index operator is bound higher than dereference.
So in case
*teamToRead[currentPlayersNumber][otherNumber] = 20;
you are trying to say something like
*(* ( teamToRead + currentPlayersNumber ) ) [otherNumber] = 20;
where pointer arithmetic becomes illegal as they respect the pointer type and thus out of bounds.
To solve this problem, you need to ensure dereferencing priority by explicit parentheses, for example
(*teamToRead)[currentPlayersNumber][otherNumber] = 20;
source to share
Another option is to give up the pointer to the 2-dimensional array and just use the pointer to (the first from the array) of the one-dimensional array:
int Team1[12][8];
int readLineupB(int teamNr){
// declare teamToRead as a pointer to array of 8 ints
int (*teamToRead)[8];
// Team1 is of type int x[12][8] that readily decays
// to int (*x)[8]
teamToRead = Team1;
for (int currentPlayersNumber = 1; currentPlayersNumber<11; currentPlayersNumber++) {
for (int otherNumber = 1; otherNumber<7; otherNumber++) {
// no dereference here.
teamToRead[currentPlayersNumber][otherNumber] = 20;
}
}
return 0;
}
source to share