Changing values ​​in an array from a pointer?

I played with pointers to help better understand. I declared aas a pointer to an array of integers of length 3 and bas an array of integers of length 3. Then I point ato b.

int main()
{
    int (*a)[3];
    int b[3] { 2, 4, 6 };
    a = &b;
    a[0][0] = 8;
    // This prints out 8 and 8.
    std::cout << a[0][0] << "\t" << b[0];

    // This prints out 0x28fecc and 8.
    std::cout << a[0] << "\t" << b[0];

    return 0;
}

To access an element bthrough a pointer a, I need to do a[0][0]as if they were an array of arrays. This compares to declaring a pointer to an array of integers using a new keyword, where I can simply output c[0].

int* c = new int[3] { 2, 4, 6 };
std::cout << c[0];

Why is this?

Thank you very much george

+4
source share
5 answers

a[0][0], a .

, a , *a, (*a)[0] , , a[0][0].

, , a ( , c ):

int * a = b;

a[i] i , .

+4

a , (*a)[0]. a[0], , *a, , , .

c , , , .

+1

a

int *a;

a = b;
std::cout << a[0];

8
+1

, .

int* c = new int[3] { 2, 4, 6 };

int * c. ,

int *a;
int b[3] { 2, 4, 6 };
a = b;

, :

a[0] = 8;

a = b;

b , b int *

0

.

b int b[3]; ( ) b[0].

a int (*a)[3]; (*a)[0].

" ", , . -, " " - *a. a, , . , . , a = &b, *a == b.

, a[0][0]? , [] (, , "" ). a[N] C , *(a + N); a[0] - *a, . , a[0][0] (*a)[0] , [], , .

0

All Articles