Last active
March 20, 2017 19:31
-
-
Save mesbahamin/a375cb75a6c61c7ab11cb987940c7637 to your computer and use it in GitHub Desktop.
Basic examples of pointers, the dereference operator, and the address of operator.
This file contains hidden or 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
#include <iostream> | |
using namespace std; | |
int main() | |
{ | |
int num; | |
cout << "The address of 'num': " << &num << endl; | |
//Here, the '*' says numptr is a pointer that holds the address of an int | |
int *numptr; | |
numptr = # | |
cout << "The address numptr is pointing to: " << numptr << endl; | |
num = 12; | |
cout << "The value of 'num': " << num << endl; | |
//Here, the '*' dereferences numptr | |
cout << "The value 'numptr' is pointing to: " << *numptr << endl; | |
//We change the value at the address to 24 | |
*numptr = 24; | |
cout << "The value 'numptr' is pointing to: " << *numptr << endl; | |
cout << "The value of 'num': " << num << endl; | |
char *my_char = new char; | |
// TODO: Why doesn't this print out the address??? | |
cout << "The address my_char is pointing to: " << my_char << endl; | |
*my_char = 'a'; | |
cout << "The value 'my_char' is pointing to: " << *my_char << endl; | |
char *my_string = new char[7]; | |
my_string[1] = 'z'; | |
cout << "The second char of my_string is: " << my_string[1] << endl; | |
*(my_string + 1) = 'x'; | |
// pointer points to an address e.g. 0x7ffd3520001c | |
// When you add 1 to my_string, you increment that address | |
// by 1 * sizeof(char); | |
// In memory a char array looks like: | |
// ____ ____ ____ ____ ____ ____ ____ ____ | |
// 0 1 2 3 4 5 6 7 | |
// my_string[1] == *(my_string + 1) | |
// my_string[2] == *(my_string + 2) | |
cout << "The second char of my_string is: " << *(my_string + 1) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment