0

I am working with dynamic arrays in C++ and trying to assign a memory allocation. But, as I debug, I found out that the memory is not being allocated.

In header file:

Data *_elements;

In cpp file constructor:

_elements = new Data[10];

where Data is a struct, consisting a string type and int type.

While I am debugging, I noticed that the elements are not being assigned with 10 memory allocations. enter image description here

I would like to know what is that I am doing wrong. Thank you!

gsasikiran
  • 99
  • 1
  • 6
  • 2
    What evidence do you have that "the elements are not being assigned with 10 memory allocations"? Why do you think there *should* be 10 allocations, as opposed to one big one? – Scott Hunter Dec 23 '20 at 13:37
  • 1
    Your debugger does not show all elements of the array. You can watch content with indices like `_elements[1]` – Ismail Durmaz Dec 23 '20 at 13:39
  • Thank you @İsmailDurmaz. Apparently, my debugger is not showing it! – gsasikiran Dec 23 '20 at 13:43
  • 1
    @SasiKiranGaddipati -- You should have always suspected that it is the tool you're using to view the variables, and not the program itself. It would be a big joke if a C++ compiler didn't produce the correct code to do a simple `new[]`. – PaulMcKenzie Dec 23 '20 at 13:46
  • 1
    fyi, `_elements` is a pointer, not an array, you just make it point to an array. – Raildex Dec 23 '20 at 13:49
  • If you use Visual Studio you probably want to read about this method to get the debugger to show you the values of a dynamically allocated array: [https://stackoverflow.com/questions/75180/how-to-display-a-dynamically-allocated-array-in-the-visual-studio-debugger](https://stackoverflow.com/questions/75180/how-to-display-a-dynamically-allocated-array-in-the-visual-studio-debugger) – drescherjm Dec 23 '20 at 14:51

1 Answers1

0

I'm pretty sure that the memory is being allocated, it's just not showing up. If you perform anything using these memory locations you will have them show up in your debugger. For example:

//you have something like this in some statement
element[i] //where i is some variable between and including 1-9. lets say 3

You will have element[3] show up in the debugger.

P.S. I'm starting out with C++, and programming as a whole, so please do correct me if I am wrong.

OctaveL
  • 1,017
  • 8
  • 18