0
Pointers, arrays and variables in C++
So, i'm trying to get a value from a 2d array, and stored it in a int variable, but something strange happens. I still didn't get exactly how pointers work, so probably i'm making some mistake about it. This is how I declared it: int my_array = [3][2]; int auxiliar; auxiliar = my_array[2][1]; But this is not heppening, I already tried to use: auxiliar = &my_array[2][1]; auxiliar = *my_array[2][1]; but none of it pass the value at my_array[2][1], or i get some error about the tipo of auxiliar and my_array;
2 Antworten
+ 4
The first problem as Jay Matthews pointed out is the illegality of the array of arrays' (2D array) syntax. In general, an integer 2D array can be declared as
int arr[row][column]; (both row and column are fixed) ( e.g. int my_array[3][2]; )
or as pointer to array as
int *arr[column]; // same as int arr[][column] (row is expandable to hold more elements)
or as pointer to pointer
int **arr; // (expandable in both direction)
where row and column are conceptually/conventionally gets named. Behind the scene, the whole thing occupies a contiguous chunk of memory.
Next is, the initial values of the array. Assume you perfectly declared it, now it must hold some data in order to get processed later on. You'd either do it manually or through a loop.
Next is, the integer variable. it only can hold an integer literal not the address of another variable. To do such thing, you need to assign the address to a pointer as
int *p = &my_array[0][0];
And dereferencing a literal value is a compilation error as in
...
+ 4
...
*my_array[0][0] which is equivalent to **(*my_array + 0)
( my_array[0][0] is equ. to *(*my_array + 0) )
suppose the value inside [0][0] is 10, then by the above assumption you are performing *10 which is meaningless.
_____
For further examples and explanations visit the following link
[ https://www.learncpp.com/cpp-tutorial/65-multidimensional-arrays/ ]