Difference between two C ++ array declaration methods

These are two of probably many ways to declare arrays (and allocate memory for them) in C ++

1. int a[3];

2. int *b = new int[3];

I want to understand how C ++ handles two differently.

and. In both cases, I can access the array with the following syntax: a[1]andb[1]

b. When I try cout<< aand cout<< b, both print the addresses of the first element of the corresponding arrays.

It seems to me that both a and b are considered as pointers to the first elements of arrays.

with. But oddly enough, when I try to do cout << sizeof(a)and sizeof(b), they print different values ​​- 4 and 12. respectively.

I do not understand why in the case the sizeof(b)size of the entire array is printed.

+5
source share
5 answers

a- array (type int [3])
bis a pointer (type int*)

In C ++, they are completely different things.

sizeofan array is the number of elements times the size of each element.
The pointer sizeofis independent of the size of the array (usually 4 or 8 bytes).

The only thing that unites arrays and pointers is that arrays often "break up" into pointers in several situations. This is what happens when you print out their value.

+8
source

, , a b . b . a - .

( ) . a ( , int double), . , int i. i - , (4 ). , a - , , (12 ).

b . 12 , ( new int[3]). b 4- , int 12- .

, . C++. , [] . , (, void Foo(int a[3]);, a , ). - ( ), .

+3

1 . , .

2 . . , new[], delete[]:

int* b = new int[3];
delete[] b;
0

++ ,

int array[10];
sizeof(array) needs to be compile-time constant and
sizeof(array[0])==sizeof(array[1])==...==sizeof(array[9])

++ , . ( )

0

(# 1) , . (# 2) , ( , ).

, : :

-1