-3

I am working on an assignment for my c++ class where I need to dynamically assign a new int, array, and pointer from another pointer to practice dynamic memory allocation.

At first, I was struggling with creating a new int to provide an int for my new array, but I got it to compile and was wondering if my declarations were correct.

int *dmaArray = new int;
*dmaArray = 4;

I then took that and put it into a dynamically created array, but I don't know how to declare values of the array as it errors out saying "cannot convert to int". I did some thinking and I believe it's because it was declared and needs to be initialized at the declaration; I can't because the declaration is already a declaration (new) in itself.

int * nodeValues = new int[*dmaArray];
nodeValues[*dmaArray] = {6, 2, 28, 1};

A loop wouldn't work to assign values after since the values aren't consecutive or in any pattern. (well, regardless, I would need to use an array because the assignment said so.

  • 1
    Your code is super confused. Shouldn't they tell you in your class how to do this? – Max Vollmer Apr 28 '18 at 20:05
  • Possible duplicate of [How do I use arrays in C++?](https://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c) – Max Vollmer Apr 28 '18 at 20:06
  • You have some basic understanding problems. I would recommend going through a [good book](https://stackoverflow.com/q/388242/9254539). – eesiraed Apr 28 '18 at 20:25

2 Answers2

1

This is not how to to declare a dynamic array and initialize it:

int * nodeValues = new int[*dmaArray];
nodeValues[*dmaArray] = {6, 2, 28, 1};

So you declare it this way:

int* nodeValues = new int[dmaArray];

And to assign values to it use loops or manually:

nodeValues[0] = 6;
nodeValues[1] = 2;
nodeValues[2] = 28,
nodeValues[3] = 1;

Remember arrays use indexes to read/write its elements as the fact being some sort of data of the same type contiguous to each other in memory.

So if you want to print the array:

for(auto i(0); i != dmaArray; ++i)
    std::cout << nodeValues[i] << ", ";

Finally you should clean memory dynamically allocated after finishing with it because the compiler doesn't do it for you:

delete[] nodeValues;
Raindrop7
  • 3,889
  • 3
  • 16
  • 27
0

I figured out how:

int * nodeValues = new int[*dmaArray]{6,5,28,1};