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:
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.
C
and C++
are same in terms of an array which has automatic storage allocation.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments