0
votes

Consider the following code:

#include <iostream>

int main()
{
    int index;
    std::cin >> index;

    int* dynArray = new int[5];
    dynArray[index] = 1;

    int stackArray[5];
    stackArray[index] = 1;
}

I know for sure that dynArray is a simple int* pointer and it takes additional sizeof(int*) bytes on stack.

Question 1: Is an additional pointer variable also created on stack for stackArray? If so, does that always happen? If not, then how does stackArray[index] = 1; work without knowing array base, i.e. how does the compiler decide what value to add to index for calculating address?

Question 2: Is there any difference between C/C++?

I want an answer for these 2 environments:

  1. GCC/Linux, x86
  2. Visual Stuidio 2013, x86
2
@ArunMu That has little relation to the question. - Babken Vardanyan
For first, int* dynArray = new int[5] is not the same type as int stackArray[5]. - 101010
@40two Correct, that's why I am asking this question. - Babken Vardanyan
using gcc you can compile the code using the -S flag to generate the assembly code and verify by yourself how the two arrays are allocated. I would expect the dynArray to be in the heap though. Don't know if there is a similar option for VS2013 - sergico

2 Answers

6
votes
  • dynarray is a variable. Its type is int *, and it has automatic storage duration ("on the stack"). Its value is a pointer to some element somewhere else. The fact that it happens to point to an element of some array somewhere else is to some extent incidental.

  • stackArray is a variable. Its type is int[5] and it has automatic storage duration. Its value is an array of five integers. When you use the name of the variable in an expression like stackArray[index], that expression denotes the corresponding array element (which is a subobject of the array object).

Note that in your example, the array of which dynarray[index] is an element is not itself a variable, nor is the element itself. You can only access the element objects because you have a pointer to them. (And in fact you cannot express the array object itself at all, since its type is know knowable at compile time. Dynamic arrays are the one part of C++ where you have truly dynamic typing.)

5
votes
  1. stackArray is an array, not a pointer. Its type is int[5], i.e., an array of 5 integers. The compiler knows the type of elements of the array which is int. stackArray[index] is evaluated to *(stackArray + index). Here, the array stackArray evaluates to a pointer to its first element.

  2. C and C++ are same in terms of an array which has automatic storage allocation.