C and C++ arrays and Pointers and references

  • 2020-05-26 09:50:59
  • OfStack

C/C++ arrays and Pointers and references

1. The difference between an array and a pointer

(1) definition

An array is a symbol, not a variable, and therefore has no storage space of its own. However, the pointer is a variable, and the contents stored in it are the address of another variable. Because it is a variable, the pointer has its own memory space, but the contents stored in it are special.

(2) differences

a. For declarations and definitions, Pointers and arrays are not the same. If an array is defined, the declaration should also be an array
b. Pointers and arrays are equivalent when used as subscript operators. a[i] is translated by the compiler to *(a+i).
c. When an array declaration is used as a functional parameter, the array is actually used as a pointer.

(3) analysis from the perspective of assembly

**int i = 10;**
00C44CC8 mov     dword ptr [i],0Ah 
**int * p = &i;**  ( 1 ) 
00C44CCF lea     eax,[i] 
00C44CD2 mov     dword ptr [p],eax 
**int arr[5] = {0};** ( 2 ) 
00C44CD5 mov     dword ptr [arr],0 
00C44CDC xor     eax,eax 
00C44CDE mov     dword ptr [ebp-30h],eax 
00C44CE1 mov     dword ptr [ebp-2Ch],eax 
00C44CE4 mov     dword ptr [ebp-28h],eax 
00C44CE7 mov     dword ptr [ebp-24h],eax 


(1) lea first takes the address of i and stores it in the space pointed by p, which is enough to prove that p has its own space.

(2) no space is allocated to the array

2. Difference between arrays and references

(1) definition

A reference is an alias given to a variable. The reference must be initialized, reference 1 cannot be changed by definition, and the initialized value must be able to fetch the address, access the reference variable, and always access the memory of the variable it refers to.

(2) differences

There are no references in C, only level 1 references before C++11, followed by left and right references.

(3) assembly Angle

**int i = 10;**
00ED4CBE mov     dword ptr [i],0Ah 
**int &a = i;**
00ED4CC5 lea     eax,[i] 
00ED4CC8 mov     dword ptr [a],eax 

If you have any questions, please leave a message or come to this site community to exchange discussion, common progress, thank you for reading, hope to help to everyone, thank you for your support of this site!

Related articles: