Dynamic Arrays

Hey guys,

I have two short questions on Pointers. Lets say i want to create an integer array with four entries.

1
2
3
4
5
6
	
int * mypntr;
mypntr = new int[4];
mypntr[0] = 1;
mypntr[1] = 2;
// ect... // 


That should work. Now first, is there a a way to declare mypntr like
 
*mypntr = {1,2,3,4};

or do i have to do it element-wise?


Now to my second question. The following code also seems to work for the array declaration.

1
2
3
4
5
int arr;
int *arrp=&arr;
*arrp = 1;
*(arrp + 1) = 2;
*(arrp + 2) = 3;


Is wonder if i overwrite some other memory since no array-size has to be defined. Should i avoid the second option?

Thanks for your feedback and cheers,
Sam
Last edited on
Now first, is there a a way to declare mypntr like

Do you mean something like: int mypntr[] = {1,2,3,4};? But understand this is no longer a dynamic array.

Is wonder if i overwrite some other memory since no array-size has to be defined.

Yes, you are overwriting some other memory location.

closed account 5a8Ym39o wrote:
You can try

No. That does not do the same thing at all. That simply creates a pointer to an array created on the stack. The OP was asking about initialising a dynamically allocated array on the heap.

As a general rule, ignore everything closed account 5a8Ym39o posts. He's a troll, who frequently posts unhelpful and incorrect "advice".
Last edited on
int* p = new int[4] { 1, 2, 3, 4 } ;
http://coliru.stacked-crooked.com/a/1ebd5d7daaf25fc1
cool ok! thanks!

What about an array of the class Inhabs. Will the memory nicely be managed in the following code?

1
2
3
4
5
Inhabs * inh;
Inhabs ** inhp = &inh;
for (int i = 0; i < nums; i++) {
	inhp[i] = new Inhabs();
}

Thnks for inputs and cheers!
Last edited on
> What about an array of the class Inhabs.

Strongly favour std::vector<> over primitive variable-length arrays.
See: http://www.cplusplus.com/forum/beginner/186249/#msg908092
I'm trying to learn working with pointers for my exam. Does this make more sense?

1
2
3
4
5
Inhabs * inh[num];
Inhabs ** inhp = inh;
for (int i = 0; i < nums; i++) {
	inhp[i] = new Inhabs();
}
Yes, it does.

On line 1, you are allocating space on the stack for num pointers.

On line 2, you are creating a pointer to a pointer, that's equal to inh - although there's not much reason to do that.

On line 4, you are dynamically allocating memory on the stack for an Inhabs object, and setting the value of one of the elements of your inh array to be the address of that new object.
Last edited on
Topic archived. No new replies allowed.