#include <stdio.h>
void init_tableau2D(int **t ,int ligne ,int colonne){
int i,j;
for(i=0;i<ligne;i++){
for(j=0;j<colonne;j++){
printf("%d\n",t[0][0]);
}
}
}
int main()
{
int tab[3][2]={{5,8},{11,6},{37,45}};
/* Here I have allocated staticly a 2D table*/
init_tableau2D(tab,3,2);
return 0;
}
Why does using a static allocated 2D table on a function with pointer** results a segmantation fault
Asked
Active
Viewed 68 times
0

haccks
- 104,019
- 25
- 176
- 264

Mr.Jupiter
- 47
- 1
- 7
-
1`tab` does not decay to `int **`, it decays to `int (*)[2]`. – Osiris Oct 15 '18 at 12:32
-
`int **t` should be `int t[3][2]`. – haccks Oct 15 '18 at 12:33
-
1Please make sure you have enabled warnings on your compiler. You should see warning or error on mismatching types. – user694733 Oct 15 '18 at 12:33
-
You are probably interested in https://stackoverflow.com/questions/3911400/how-to-pass-2d-array-matrix-in-a-function-in-c – hellow Oct 15 '18 at 12:37
1 Answers
1
Arrays decay to pointers if you pass them as parameter, but tab
in your example decays to int (*)[2]
and not to int **
. To make it work you need to change the function definition to:
void init_tableau2D(int ligne ,int colonne, int t[ligne][colonne])

Osiris
- 2,783
- 9
- 17
-
Can you explain more about why does the tab has been casted to an **int(\*)[2]** and not to an **int\*\*** ? – Mr.Jupiter Oct 15 '18 at 12:52
-
@RookedBishop In most cases arrays decay to pointers to its first element, like if you pass them as parameter. `int [n]` will become `int *`. But if you have an array of arrays, the first element is an array and therefore it decays to a pointer to an array. So `int [3][2]` will decay to `int (*)[2]`. – Osiris Oct 15 '18 at 12:56
-
@RookedBishop [This](https://stackoverflow.com/questions/4470950/why-cant-we-use-double-pointer-to-represent-two-dimensional-arrays) is maybe useful too. No problem. – Osiris Oct 15 '18 at 13:01