ITC Lect 18 (Pointers and Strings - II)
ITC Lect 18 (Pointers and Strings - II)
Example
int main() {
int x = 10;
int* y = &x;
cout << *y;
}
Prints the value 10 – the value in the variable at the address stored in y
In other words, the value to which y points
Another Example
int main() {
int x = 10;
int* y = &x;
x = 20;
cout << *y;
}
Prints the value 20
A Third Example
int main() {
int x = 10;
int* y = &x;
*y = 20;
cout<<x<<*y;
}
Prints: 20, 20 – we can use *y as a left-hand value, which changes the contents
of the address that y points to
A Last Example
int main() {
int x = 10;
int* y = &x;
y = 20;
cout<<x<<*y;
}
Prints: 10, ??? – the second term will be what ever happens to be at
bytes 20, 21, 22 and 23 – could be junk.
It will look at all four bytes because it’s a pointer to an int – which is a
four-byte data structure
Arrays of Pointers
• Arrays can contain pointers
– Commonly used to store an array of strings
char *suit[ 4 ] = {"Hearts", "Diamonds",
"Clubs", "Spades" };
– Each element of suit is a pointer to a char * (a string)
– The strings are not in the array, only pointers to the strings are in the
array
suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\
suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ 0’
’d’ ’s’ ’\
suit[2] ’C’ ’l’ ’u’ ’b’ ’s’ ’\ 0’
References
Dietal and Dietal : How to Program C++
3rd Edition