Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ array pointer

Tags:

c++

arrays

I came across a C++ program like this

#include<iostream>
using namespace std;

int main() {
    int N = 10;
    int M = 2;
    int a[] = { 2,1,4,3,6,5,8,7,10,9 };
    int(*b)[5] = (int(*)[5]) a;
    for (int i = 0; i<M; i++) {
        for (int j = 0; j<N / M; j++) {
            cout << b[i][j] << endl;
        }
    }

    system("pause");
    return 0;
}

The above program's output is 2,1,4,3,6,5,8,7,10,9. It looks like b is an array point. So what does (int(*)[5]) a mean? Can someone help me to explain it?

like image 948
lbs0912 Avatar asked Jun 18 '26 08:06

lbs0912


1 Answers

a is an int-array with 10 elements: int [10]. b is a pointer to an int-array with 5 elements: int (*) [5]. b is initialized with the value of a and explicitly casted using the C-style cast: (int(*)[5]) a.

Effectively a is a 1x10 matrix and b is a 2x5 matrix, it is in fact a "reshape" of a into b, with the same content. The "most" dangerous thing here is that the reshape does not perform a deep copy, i.e., changes to b also affect a and vice versa;

The type, here int, is completely irrelevant. Here is an online example, with several different types.

like image 81
Jonas Avatar answered Jun 20 '26 21:06

Jonas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!