Last active
March 17, 2017 10:05
-
-
Save gpetuhov/81b09da1a69bb0645c02c409da86ee65 to your computer and use it in GitHub Desktop.
C++ Pointers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int x = 0; | |
int* ptr; | |
x = 10; | |
ptr = &x; // Save address of x into ptr | |
cout << "X = " << x << endl; // Result is 10 | |
cout << "Y = " << *ptr << endl; // Result is 10 | |
// ============ | |
struct TwoNumbers { | |
int x; | |
int y; | |
}; | |
TwoNumbers numbers; | |
TwoNumbers* nptr; | |
numbers.x = 5; | |
numbers.y = 9; | |
nptr = &numbers; // Save address of numbers into nptr | |
cout << "Numbers.x = " << nptr->x << endl; // Result is 5 | |
cout << "Numbers.y = " << nptr->y << endl; // Result is 9 | |
// ============ | |
int* a; | |
int b[2]; | |
a = b; // Now a points to first element of b | |
b[0] = 7; | |
b[1] = 10; | |
*a++; // Here a is incremented (not the first element of b), so now a points to second element of b | |
cout << *a << endl; // Result is 10 (second element of b) | |
// ============ | |
int* aaa; | |
int bbb = 7; | |
aaa = &bbb; // Save address of bbb into aaa | |
bbb += 7; // Now bbb is 14 | |
(*aaa)++; // Here we increment variable at address kept in aaa (this is bbb), so bbb now is 15 | |
cout << aaa << endl; // Result is address kept in aaa | |
cout << *aaa << endl; // Result is 15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment