Array of pointers C++ creates of copy

I think you wanted to do this

int main(int argc, char *argv[])
{

    int a[] = { 1, 2, 3, 4, 5 };
    unsigned max=sizeof(a) / sizeof(a[0]);
    int **b = new int*[max];

    for (int i = 0; i < max; i++)
    {
        b[i] = &a[i];
    }

    unsigned max=sizeof(a) / sizeof(a[0]);
    for (int i = 0; i < max; i++)
    {
         std::cout << "b[" << i << "]:" << *b[i] << std::endl;
         std::cout << "a[" << i << "]:" << a[i] << std::endl;
    }
    delete[] b;

    return 0;
} 

Two mistakes. First, when you declare array of pointers you use

int **b;

Secondly, to determine size of array you can use

sizeof(a) / sizeof(a[0])

but be careful here. After passing your array as argument into function it won’t work any longer.

Leave a Comment