1

i create an Array with 3 numbers; i see only one number instead 3

int *ArrayA;
ArrayA = new int[3];
ArrayA[0] = 2;
ArrayA[1] = 4;
ArrayA[2] = 6;

when i debugging and follows ArrayA i see only 2; what could be the problem?

Alex
  • 13
  • 4
  • 4
    Please make a [mre]. e.g. how are you printing the values? – cigien Aug 12 '20 at 17:51
  • 5
    If you're looking at it in a debugger, the debugger is completely unaware that `ArrayA` points to the first element of an array. – molbdnilo Aug 12 '20 at 17:53
  • 1
    What debugger are you using? Here's the [dupe](https://stackoverflow.com/questions/75180/how-to-display-a-dynamically-allocated-array-in-the-visual-studio-debugger) if you're using VS – cigien Aug 12 '20 at 17:56
  • 4
    If you're using the Visual Studio debugger you can specify how many elements you want to display in the watch window: `ArrayA, 3` will show 3 elements. – Timo Aug 12 '20 at 17:56

2 Answers2

2

Your object ArrayA is of type int *. Hence it points to a single int. The fact that you have it point at an int[3] array doesn't change that fact. Your debugger can also not guess that you want it to display more than one value.


Instead of using raw c-style arrays, it is usually recommended to use an std::array.

std::array<int,3> arrayA = {2,4,6};
bitmask
  • 32,434
  • 14
  • 99
  • 159
  • 1
    And if you won't always have a size of `3`, consider using [`std::vector`](https://en.cppreference.com/w/cpp/container/vector). because you can change the size to whatever you need (within reason, of course). – user4581301 Aug 12 '20 at 18:20
1

This is not a problem. It's as expected because ArrayA is a pointer. So pointer base address and the address of the 1st element of the array are same. Hence you always see 2 in your debugger. Not sure which debugger you are using, you can try to add ArrayA[index] or *(ArrayA + index) then you can see other values as well.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70