Skip to content

Instantly share code, notes, and snippets.

@natemcmaster
Created September 25, 2013 16:37
Show Gist options
  • Save natemcmaster/6702360 to your computer and use it in GitHub Desktop.
Save natemcmaster/6702360 to your computer and use it in GitHub Desktop.
Tutoring: sample of how to various ways use pointers.
#include <iostream>
#include <string>
using namespace std;
void appendAuthorName(string* bookTitle){
*bookTitle = *bookTitle + ": by J.K. Rowling"; // notice how I am modifying bookTitle but not returning anything. I am modifying the string directly
}
int main(){
string* novel=new string("The Sound and the Fury"); // this does 2 things. 1-creates a new pointer, 2- places the string 'The Sound and the Fury' on the memory heap
cout << novel << endl; // This prints the memory address of the pointer
cout << *novel << endl; //This prints the string "The Sound and the Fury". Using *novel is called dereferencing a pointer.
delete novel; // This deletes the string "The Sound and the Fury" from the heap, but does not delete the pointer itself.
novel = new string("Harry Potter and the Sorcerer's Stone");
cout << *novel << endl; // Notice how I can still use the pointer (novel) by reassigning it to a new string
delete novel;
string sequel="Harry Potter and the Chamber of Secrets"; // This creates a string on the stack (not the heap)
novel = &sequel; // Using &sequel returns the memory location of sequel. Now novel is assigned to the location of sequel;
cout << novel << endl; //
cout << &sequel << endl; // These two lines should print the same thing
cout << *novel << endl; // Prints the value of sequel ('Harry Potter and the Chamber of Secrets')
appendAuthorName(novel);
cout << * novel << endl; // Notice how novel is now different, even though appendAuthorName does not return a string.
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment