There's no way for C to know how your indexing is supposed to work: there's no information that associates the number of columns (col
) with myArray
. When you do myArray[i][j]
with myArray
declared as int * *
, C will first evalutate myArray[i]
, i.e. read the i:th value of myArray
as if it were an integer pointer, which it isn't in your case. It will then index j
from that invalid value, likely generating the segmentation fault (at least causing undefined behavior).
When doing it manually like that, you have two choices:
- Make it "jagged", where each row has its own pointer to that row's elements. This is what @bgamlath suggests in his answer.
- Do the indexing yourself, by replacing
myArray[i][i]
withmyArray[i * cols + j]
.
The latter uses less memory and (way) less memorhy allocations, which is nice. Of course the indexing can be a bit awkward.