Arrays and pointers are two types. Array names can be implicitly converted to pointers to the first element. The type of a is int[5], and sizeof(a) is equivalent to sizeof(int[5]) rather than sizeof(int *).
There is still a difference between array pointers and ordinary pointers. After all, when the array is defined, its element type and number can be determined
Only when the compiler cannot infer whether it is an array or an ordinary pointer, it will be calculated based on the size of an ordinary pointer sizeof For example, in a function declaration, void f(int* a), because any pointer may be passed as the parameter a Enter, it is impossible for the compiler to infer whether it is an array so sizeof(a) = sizeof(int*)
But in the case of your question, the compiler can clearly infer that a is a 5-element integer array, so sizeof(a) = sizeof(int[5])
To put it simply, the essential difference: The variable name is the name of the memory area and has no name at runtime. a and p are only meaningful in source code and compilation time. The memory named a is a piece of memory of type int[5] with 5 ints. p is named a memory space with only one int pointer of type int. a[2] is directly translated into the third unit of that memory space during compilation. p[2] is translated into p, take out the value of the int* memory space, and add 2 to get the memory address of the memory space. int const p only limits the memory space pointed by p to only have one int pointer to be immutable.
Arrays and pointers are two types.
Array names can be implicitly converted to pointers to the first element. The type of
a
isint[5]
, andsizeof(a)
is equivalent tosizeof(int[5])
rather thansizeof(int *)
.There is still a difference between array pointers and ordinary pointers. After all, when the array is defined, its element type and number can be determined
Only when the compiler cannot infer whether it is an array or an ordinary pointer, it will be calculated based on the size of an ordinary pointer
sizeof
For example, in a function declaration,
void f(int* a)
, because any pointer may be passed as the parametera
Enter, it is impossible for the compiler to infer whether it is an arrayso
sizeof(a) = sizeof(int*)
But in the case of your question, the compiler can clearly infer that
a
is a 5-element integer array, sosizeof(a) = sizeof(int[5])
To put it simply, the essential difference:
The variable name is the name of the memory area and has no name at runtime. a and p are only meaningful in source code and compilation time.
The memory named a is a piece of memory of type int[5] with 5 ints.
p is named a memory space with only one int pointer of type int.
a[2] is directly translated into the third unit of that memory space during compilation.
p[2] is translated into p, take out the value of the int* memory space, and add 2 to get the memory address of the memory space.
int const p only limits the memory space pointed by p to only have one int pointer to be immutable.