Is there any difference between these two declarations?
int x[10];
vs.
int* x = new int[10];
I suppose the former declaration (like the latter one) is a pointer declaration and both variables could be treated the same. Does it mean they are intrinsically the same?
To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100}; We have now created a variable that holds an array of four integers.
These elements are numbered from 0 to 4, with 0 being the first while 4 being the last; In C++, the index of the first array element is always zero. As expected, an n array must be declared prior its use. A typical declaration for an array in C++ is: type name [elements];
type var-name[]; OR type[] var-name; An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array.
If you want to initialize an array, try using Array Initializer: int[] data = {10,20,30,40,50,60,71,80,90,91}; // or int[] data; data = new int[] {10,20,30,40,50,60,71,80,90,91};
#include<iostream> int y[10]; void doSomething() { int x[10]; int *z = new int[10]; //Do something interesting delete []z; } int main() { doSomething(); }
int x[10];
- Creates an array of size 10 integers on stack.
- You do not have to explicitly delete this memory because it goes away as stack unwinds.
- Its scope is limited to the function doSomething()
int y[10];
- Creates an array of size 10 integers on BSS/Data segment.
- You do not have to explicitly delete this memory.
- Since it is declared global
it is accessible globally.
int *z = new int[10];
- Allocates a dynamic array of size 10 integers on heap and returns the address of this memory to z
.
- You have to explicitly delete this dynamic memory after using it. using:
delete[] z;
The only thing similar between
int x[10];
and
int* x = new int[10];
is that either can be used in some contexts where a int*
is expected:
int* b = x; // Either form of x will work void foo(int* p) {} foo(x); // Either form will work
However, they cannot be used in all contexts where a int*
is expected. Specifically,
delete [] x; // UB for the first case, necessary for the second case.
Some of the core differences have been explained in the other answers. The other core differences are:
Difference 1
sizeof(x) == sizeof(int)*10 // First case sizeof(x) == sizeof(int*) // Second case.
Difference 2
Type of &x
is int (*)[10]
in the first case
Type of &x
is int**
in the second case
Difference 3
Given function
void foo(int (&arr)[10]) { }
you can call it using the first x
not the second x
.
foo(x); // OK for first case, not OK for second case.
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