NewbieDave
NewbieDave

Reputation: 1259

C++ Pointer Array

I just have a basic question regarding the pointer array.

int *Arr[8]; // An array of int pointers

int (*Arr)[8]; // A pointer pointing to an int array

If I use the second one, how do I assign integers to the array? I know if were on the heap

int *Arr = new int[8]

I can just do Arr[5] = 99. How do I do this on the stake?

Thank you very much for your help.

Upvotes: 2

Views: 302

Answers (2)

Nikos C.
Nikos C.

Reputation: 51832

Given this declaration:

int (*Arr)[8];

you can assign it the address of an int array of size 8:

int data[8];
Arr = &data;

You can modify data through Arr:

(*Arr)[i] = value;

Note the parentheses around *Arr. They're needed to dereference Arr before applying the index to it, since the index [] operator has a higher precedence.

An important thing to understand here is that data is not dynamically allocated. If you keep its address around after it has gone out of scope, you'll get a dangling pointer (a pointer that points to something that no longer exists.)

To dynamically allocate an array and assign it to Arr, you can use a typecast on the result of new as follows:

int (*Arr)[8] = reinterpret_cast<int(*)[8]>(new int[8]);

(A working example can be found on ideone.)

Of course it doesn't make much sense to do this in such a roundabout way, as you can instead just:

int* Arr = new int[8];

And of course you can use an std::vector instead and avoid manual memory management completely:

std::vector<int> Arr;

Which provides you with an array that grows on its own as needed.

Upvotes: 7

m-renaud
m-renaud

Reputation: 1265

Since you're using C++, is there any reason why a container such as std::array would not be applicable? For example:

std::array<int, 8> arr;
std::array<int, 8>* arr_p = &arr;

and if you didn't know the size until run-time, you could use std::vector:

std::vector<int> vec(8);

The code that you have is correct, but given that the standard libraries are available, most would probably recommend using the containers and algorithms as opposed to manually managing memory yourself which is prone to bugs and memory leaks, especially when exceptions are involved.

Upvotes: 2

Related Questions