0

In the following program, I am allocating a new array on the stack and one on the heap. The type of the stack allocated array is int and the type of the heap allocated array is int*. However, when passed into PrintArray they appear to both be int*. Why is the type of the stack allocated array not explicitly written as int* on declaration?

#include <iostream>

void PrintArray(int* array, int count) {
    for (int i = 0; i < count; i++)
        std::cout << *(array + i) << std::endl;
}

int main(int argc, char* argv[]) {
    const int count = 5;
    int stackAllocated[count];
    int* heapAllocated = new int[count];

    for (int i = 0; i < count; i++) { 
        stackAllocated[i] = i;
        *(heapAllocated + i) = i;
    }

    PrintArray(stackAllocated, count);
    PrintArray(heapAllocated, count);

    delete[] heapAllocated;
}
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
transporter_room_3
  • 2,583
  • 4
  • 33
  • 51
  • 2
    "The type of the stack allocated array is `int`" that statement is false. The type is `int[]`. – JHBonarius May 14 '21 at 09:30
  • 1
    _The type of the stack allocated array is `int`_ No. The type of array (on stack) is `int[]`. It decays implicitly to `int*` in most situations. However, you may compare `sizeof stackAllocated` with `sizeof heapAllocated` to see the difference. (sizeof is one of the few operators which process the array type as is.) – Scheff's Cat May 14 '21 at 09:31
  • Thank you for taking the time to answer my question. It really helps! I've upvoted your comments and will mark the question answered as soon as stackoverflow allows me. Consider this question answered :). – transporter_room_3 May 14 '21 at 09:38
  • Note that `int count = 5; int stackAllocated[count];` is not legal C++. Some compilers allow it as an extension. I changed it to `const int count = 5;` so that it's valid, since that doesn't affect the question. – Pete Becker May 14 '21 at 12:54

1 Answers1

3

The type of the stack allocated array is int and the type of the heap allocated array is int*

That is wrong. The type of the array is int [5] in both cases. Don't confuse the array with the pointer to the first element. Consider simpler example:

 int* ptr = new int;

Here ptr is of type int*, but the object you allocated is of type int.

Arrays, wether static or dynamically allocated decay to pointers to their first element when passed to functions. That does not mean that the array itself is a pointer.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185