int main(){
int right[2][3] = {
{1,4,6}, {2,7,5}
}
....
calc(right);
}
int calc(int ** right){
printf("%i", right[0][0]);
}
I calc function that calculate some numbers based on a matrix, but I dont’ know why i get seg fault when I access the variable right within the calc function. does any body know the solution?
edit:
right now that is all it’s doing at calc function. I have some calc stuff but it’s all commented out trying to figure out how to access this variable.
Two-dimensional arrays in C don’t work the way you think they do. (Don’t worry, you’re not alone — this is a common misconception.)
The assumption implicit in the code is that
rightis an array ofint *pointers, each of which points to an array ofint. It could be done this way — and, confusingly, the syntax for accessing such an array would be the same, which is probably what causes this misconception.What C actually does is to make
rightan array of 12ints, layed out contiguously in memory. An array access like thisis effectively equivalent to this:
To pass your array to the
calcfunction, you need to do this:and then call it like this:
Edit: For more background on this, the question linked to in Binary Worrier’s comment is definitely worth looking at.