2

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.

2
  • 2
    By stake I assume you mean stack? Commented Jul 27, 2013 at 20:39
  • 2
    @Borgleader Or steak, maybe? Commented Jul 27, 2013 at 20:53

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

16 Comments

@NikosC. It is. * has a lower precedence than [], doesn't it.
@H2CO3 I should get in the habbit of compiling code before posting it... :-P You're all right of course, the parens are needed.
@NikosC. Yup, no worries. It's just so common that it instantly catches my eyes and whenever I see *arr[idx], I always ask "shouldn't this be (*arr)[idx] instead?"
@Nikos.C Thank you very much. is it on the heap, the assign steps int data[8]; Arr = &data; are done by the complier?
@GrijeshChauhan Thanks. Corrected grammar and used reinterpret_cast.
|
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.