Pointers and arrays are intricately linked in the C language. In previous lessons, you learned how to declare an array of variables:
1
| int anArray[5]; // declare array of 5 integers |
1
2
3
4
5
6
7
| int anArray[5] = { 9, 7, 5, 3, 1 }; // dereferencing an array returns the first element (element 0) cout << *anArray; // prints 9! char szName[] = "Jason" ; // C-style string (also an array) cout << *szName; // prints 'J' |
pnPtr + 1
is the address of the next integer in memory after pnPtr. pnPtr - 1
is the address of the previous integer before pnPtr.pnPtr+1
does not return the address after pnPtr, but the next object of the type that pnPtr points to. If pnPtr points to an integer (assuming 4 bytes), pnPtr+3
means 3 integers after pnPtr, which is 12 addresses after pnPtr. If pnPtr points to a char, which is always 1 byte, pnPtr+3
means 3 chars after pnPtr, which is 3 addresses after pnPtr.
1
2
3
4
5
6
7
| int nValue = 7; int *pnPtr = &nValue; cout << pnPtr << endl; cout << pnPtr+1 << endl; cout << pnPtr+2 << endl; cout << pnPtr+3 << endl; |
1
2
3
4
5
6
7
| short nValue = 7; short *pnPtr = &nValue; cout << pnPtr << endl; cout << pnPtr+1 << endl; cout << pnPtr+2 << endl; cout << pnPtr+3 << endl; |
1
2
| int anArray[5] = { 9, 7, 5, 3, 1 }; cout << *(anArray+1) << endl; // prints 7 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| const int nArraySize = 7; char szName[nArraySize] = "Mollie" ; int nVowels = 0; for ( char *pnPtr = szName; pnPtr < szName + nArraySize; pnPtr++) { switch (*pnPtr) { case 'A' : case 'a' : case 'E' : case 'e' : case 'I' : case 'i' : case 'O' : case 'o' : case 'U' : case 'u' : nVowels++; break ; } } cout << szName << " has " << nVowels << " vowels" << endl; |
0 comments: