I successfully entered values to a 2D array without pointers
int main(){
int A[2][3];
for (int i=0; i<2; i ){
for(int j=0; j<3; j ){
A[i][j] = 2*i 3*j;
cout<<" "<<A[i][j]<<" ";
}
cout<<endl;
}
}
And the output is
0 3 6
2 5 8
Then I tried to reach the same outcome with pointers
int main(){
int A[2][3];
int (*p)[3] = A;
for (int i=0; i<2; i ){
for(int j=0; j<3; j ){
*(*A j)= 2*i 3*j;
cout<<" "<<*(A[i] j)<<" ";
}
cout<<endl;
}
}
And the output is
0 3 6
32758 1 0
any idea why I got a different result for the second array?
CodePudding user response:
This left operand of the assignment expression
*(*A j)= 2*i 3*j;
does not depend on the index i. In fact it is equivalent to A[0][j]
Thus elements A[1][j]
stay uninitialized.
Instead write
for (int i=0; i<2; i ){
for(int j=0; j<3; j ){
*( *( A i) j )= 2*i 3*j;
cout<<" "<<*(A[i] j)<<" ";
}
cout<<endl;
}
Or with using the declared pointer p
the program can look the following way
#include <iostream>
int main()
{
int A[2][3];
int (*p)[3] = A;
for ( int i=0; i < 2; i )
{
for ( int j=0; j<3; j )
{
*( *( p i ) j ) = 2*i 3*j;
std::cout << " " << *(A[i] j) << " ";
}
std::cout << std::endl;
}
}
That is the expression *( p i )
is the same as p[i]
and the expression *( *( p i ) j )
is the same as p[i][j]
.
CodePudding user response:
You are not using the pointer correctly. In fact, you are not even using it at all. p
is a pointer to the first int[3]
in A
. You can use the subscript operator ([]
) on it to dereference it, just like you do with A
.
#include <iostream>
int main() {
int A[2][3];
int(*p)[3] = A;
for (int i = 0; i < 2; i ) {
for (int j = 0; j < 3; j ) {
p[i][j] = 2 * i 3 * j; // proper dereferencing
std::cout << ' ' << A[i][j] << ' '; // verify via `A`
}
std::cout << '\n';
}
}