I read quite a few replies on this topic but still I can't get it. Please understand I'm in a learning process.
I have been told that a vector is nothing else than its first element address so a 2D vector.
So, why do I lose the ability to use index if I pass a 2D vector by a pointer.
int vec[10][10] = { 1, 2, 3, 4 };
int *v = vec;
why I can't say
int a = v[1][1]
as I would do with
int a = vec[1][1]
if v, that is a pointer to an int, point exactly where vec, that is a pointer to an int, point, aren't they exactly the same thing, the same object?
I read about
int (*v)[N] = vec;
where N is the number of columns.
But this appears as a super tricky thing for a beginner.
Why is this?
EDIT:
My brains came up this explanation for int (*vec)[N] meaning a pointer to a vector of 10 int.
Here it is.
Giving I understood that in a 2D array, a pointer to the first element is a pointer to an array of N elements, this is the explanation I gave myself.
If lhs of int *var = &int have to be read right to left, becoming "var is a pointer to int" then I would expect that int [N] * var = &2darray would be, right to left, "var is a pointer to an array of N int elements".
But this is syntactically incorrect to the compiler so I have to do the trick int (* vec) [N] = 2darray that, right to left, keeping in mind parenthesis priority become:
Parenthesis first, right to left: vec is a pointer.
Then the rest, that now is, right to left: int [N].
The final result is vec is a pointer to an array of N of int.
Have this even remotely any sense?
The compiler should issue a message that in this declaration
there is used a pointer of incompatible pointer type to initialize the pointer
vof the typeint *.The array
vecused as an initializer is implicitly converted to a pointer to its first element. The type of elements of this two dimensional array isint[10]. So a pointer to elements of the array will have the typeint ( * )[10].You may not use an expression like that
v[1][1]in your code snippet becuase the sub-expressionv[1]has the typeint. That is the sub-expressionv[1]produces a scalar object that is not an array. So such an expressionv[1][1]is just invalid.If you will write
then the sub-expression
v[1]yields an object of the typeint[10]that is an array. So you may apply one more the subscript operator to the obtained array likev[1][1].Pay attention to that if you have a one dimensional array like for example
then elements of this array have the type
int. And the array used in expressions with rare exceptions (as for example using insizeofoperator) is converted to a pointer to its first element of the typeint *.On the other hand, if you have a two-dimensional array like
then elements of the array are one-dimensional arrays of the type
int[n]and a pointer to elements of the array has the typeint ( * )[n].