Summarized some common pointer error-prone issues (2), pointer FAQs
4. pointers and Arrays
Some common mistakes are that arrays and pointers are completely interchangeable. Although the array name can be used as a pointer sometimes, the array name is not a pointer.
An array is a continuous set of homogeneous elements that can be accessed using indexes. (Continuous means that the element of the exponential group is adjacent in the memory, and there is no gap in the middle. homogeneous means that the element is of the same type)
Pointers are useful when processing arrays. They can be used to point to an existing array, allocate memory from the stack, and use this memory as an array.
Array/pointer Representation
Adding 1 to the array address actually adds 4, that is, the length of the integer.
#include<iostream>using namespace std;int main(){ int vector[5]={1,2,3,4,5}; int *pv=vector; int value=4; for(int i=0;i<5;i++) { *pv++ *=value; } pv=vector; for (int i=0;i<5;i++) cout<<*(pv+i)<<endl; }
Differences between pointers and Arrays
int vector[5]={1,2,3,4,5}; int *pv=vector;
The code generated by vector [I] is different from that generated by * (vector + I). The machine code generated by vector [I] notation starts from the position vector, moves the I position, and retrieves the content. The machine code generated in * (vector + I) Notation starts from the vector, adds I to the address, and then extracts the content from the address.
The sizeof operator operates differently on arrays and pointers to the same array.
Sizeof (vector) = 20; // number of bytes allocated to the array
Sizeof (pv) = 4; // pointer Length
If you allocate memory from the heap and assign the address to a pointer, you can certainly use the array subscript for the pointer and treat the memory as an array.
int *pv=(int*) malloc(5*sizeof(int)); for(int i=0;i<5;i++) { pv[i]=i+1; }
/////////////////////////////////////
for(int i=0;i<5;i++)
{
*(pv+i)=i+1;
}