Cursor and Array in C ++

Pointers and Arrays are closely related. In fact, pointers and arrays are interchangeable in some cases.

Pointers and Arrays are closely related. In fact, pointers and arrays are interchangeable in some cases. For example, a pointer that points to the array head can access that array using either an arithmetic pointer or an array index. You consider the following example:

 #include using namespace std ; const int MAX = 3 ; int main () { int mang [ MAX ] = { 10 , 100 , 200 }; int * contro ; // chung ta co mot mang dia chi trong con tro. contro = mang ; for ( int i = 0 ; i < MAX ; i ++) { cout << "Dia chi cua mang[" << i << "] = " ; cout << contro << endl ; cout << "Gia tri cua mang[" << i << "] = " ; cout << * contro << endl ; // tro toi vi tri tiep theo contro ++; } return 0 ; } 

Running the above C ++ program will produce the following results:

Cursor and Array in C ++ Picture 1Cursor and Array in C ++ Picture 1

However, pointers and arrays are not completely interchangeable. For example, consider the following program:

 #include using namespace std ; const int MAX = 3 ; int main () { int mang [ MAX ] = { 10 , 100 , 200 }; for ( int i = 0 ; i < MAX ; i ++) { * mang = i ; // Day la cu phap chinh xac mang ++; // cu phap nay la sai . Ban nen chu y. } return 0 ; } 

Applying the cursor operator * to the bearing variable is perfect, but it is not valid when modifying the bearing variable value. The reason is that the variable is a constant that points to the beginning of the array and cannot be used as l-value.

Because, an array name creates a pointer constant, it can still be used in pointer expressions, as long as it is not modified. The following example is a valid command that assigns [2] a value of 500.

 *( mang + 2 ) = 500 ; 

The above command is valid and will successfully compile because the bearing has not been changed.

According to Tutorialspoint

Previous lesson: Cursor pointer in C / C ++

Next article: Array of pointers in C ++

4 ★ | 10 Vote