Using Visual Studio Express 2013. I thought I understood static vs dynamic arrays, but the following has me confused:
int* a = new int[3]; \\ dynamic array
int** pa = &a;
int b[3]; \\ static array
int** pb = &b; \\ error: cannot convert from 'int (*)[3]' to 'int **'
Ok, so I try int (*)[3] pb = &b;
but it's not even syntactically correct. The Locals Window says pb is an int[3]
, but int[3]* pb = &b;
is also incorrect.
It also seems strange to me that b
has the same value as pa
. If I replace the declaration int b[3];
with a declaration + initialization int b[3] = {};
then that oddity disappears, so maybe it's just a VS bug:
But I still can't get at the address of the static array. If I type &b
in the Immediate Window then I get exactly the same output as if I just typed b
, which again seems strange by comparison with '&a' and 'a' which are clearly different things:
Static arrays are allocated memory at compile time and the memory is allocated on the stack. Whereas, the dynamic arrays are allocated memory at the runtime and the memory is allocated from heap. This is static integer array i.e. fixed memory assigned before runtime int arr[] = { 1, 3, 4 };
As stated earlier, static arrays are stored in the program's memory stack. Because of this is we must know the size of the array at compile time. There are two ways we can declare and initialize a static array, as shown below. // with five values.
A static array is a data structure with a fixed size. Let us see an example of a static array in C#. Here is a static string array. The data remains the same here i.e. fixed − static string[] _fruits = new string[] { "apple", "mango" };
The address of an array is the address of the first element of the array. In the above array, the first element is allocated 4 bytes. The number of the first byte is the address of the element. Similarly, the second element is also residing on the next 4 bytes.
A dynamic array is a very weird part of C++. It's a type that is never the type of any expression in the language, and you can never see a dynamic array as a whole. When you say new T[N]
, all you get is a pointer to the first element of the fictitious array of type T[N]
. (Note also that this is a truly "dynamic type"!)
By contrast, your b
is an actual array object, so naturally its address has type "pointer to array". If you wanted a pointer to a pointer its first element, you'd first have to create such a pointer:
int b[3];
int * b0 = &b[0]; // or just "int * b0 = b;" :-S
int ** pb = &b0;
Tbe variable b0
here is the analogue of your variable a
in the dynamic example - a pointer variable containing the address of the first array element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With