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:
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 ++
Discover more
Share by
Lesley MontoyaYou should read it
- Arrays and objects in JavaScript are like stories and newspapers!
- Array in Language C
- Array in Python
- Create snow effect when moving mouse on Windows
- How to Copy and Create Arrays in SketchUp
- The Quiet Details That Make a Sports Betting Platform Feel Reliable
- Instructions on creating toy set images with ChatGPT AI
- How are AI agents changing the journalism industry?
- Array of pointers in C ++
- Pointers to pointers in C ++
- Pass cursor to function in C ++