I am new to objective-c and am doing something that works for the moment but am afraid might break someday.
In one of my object, I declare a matrix of integer as instance variable. As I do not know the size of the matrix yet, I declared it like this:
int **_matrix;
Later in the code, when I know the amount of lines and columns of my matrix, I initialize it like this:
_matrix = malloc(sizeof(*_matrix) * columns * lines);
for (i = 0; i < columns; i++) {
_matrix[i] = malloc(sizeof(int) * lines);
for(j = 0; j < lines; j++)
_matrix[i][j] = -1;
}
Assuming my allocation is correct (please, feel free to tell me if it is in fact wrong), can I confidently access the elements using the 2-dimension array syntax?
I am asking because from what I read, when you create an actual 2-dimension array the memory is reserved continuously but that it might not be the case using double pointers. Therefore I am afraid that calling
_matrix[i][j]
would actually point to a random place in the memory (and not the place I allocated).
Thank you for your answers!
Yes, it's safe. It is true that two-dimensional arrays on the stack are generally allocated contiguously, but you needn't worry about that. The important thing is that the brackets are evaluated one pair at a time, not as some special [][]
operator, and brackets dereference pointers. So it will dereference your first pointer, and then it will dereference the "row" pointer that was yielded by the first dereference.
More info: Array accesses and pointer dereferences are equivalent. The expression x[y]
is equivalent to *(x+y)
. So your code first dereferences the pointer value (matrix + i)
, which gives you another pointer value (since you had an array of pointers). After this, your code dereferences the pointer (matrix[i] + j)
and assigns it the value -1. As you can see, this is precisely what you want it to do.