Skip to content

Instantly share code, notes, and snippets.

@Tevinthuku
Created December 2, 2016 13:56
Show Gist options
  • Save Tevinthuku/6a1f50b34795ba9711bd0b8961b21cbd to your computer and use it in GitHub Desktop.
Save Tevinthuku/6a1f50b34795ba9711bd0b8961b21cbd to your computer and use it in GitHub Desktop.
Most of what you need to know about pointers..
// basic pointers demo
int data = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of data in pointer variable
// prints an address
cout << "Address stored in ip variable: ";
cout << ip << endl; // prints out 8e34xA345te (An address)
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl; // prints out 20... (The actual value)\
// array of pointers
MAX = 3;
int main () {
int data[MAX] = {10, 100, 200};
int *pointer_to_data[MAX];
for (int i = 0; i < MAX; i++) {
pointer_to_data[i] = &data[i]; // assign the address of the three integers
}
}
//POINTERS POINTING TO POINTERS
int main () {
int sample;
int *ptr_to_sample;
int **pptr_to_ptr;
sample = 250;
// take the address of var
ptr_to_sample = &sample;
// take the address of ptr_to_sample using address of operator &
pptr_to_ptr = &ptr_to_sample;
// take the value using pptr
cout << "Value of sample :" << sample << endl; // prints 250
cout << "Value of *ptr_to_sample :" << *ptr << endl; // prints out an address .. i.e (3e5XCde5)
cout << "Value of **pptr :" << **pptr << endl; // prints out an address .. i.e (3e5XCde5)
return 0;
}
// ARRAYS AND POINTERS
// HOW THEY CAN WORK TOGETHER
int main () {
int MAX = 3;
int sample[MAX] = {10, 100, 200};
int *ptr;
// let us have array address in pointer.
ptr = sample;
for (int i = 0; i < MAX; i++) {
cout << "Address of sample[" << i << "] = ";
cout << ptr << endl; // the address of sample will be printed
cout << "Value of sample[" << i << "] = ";
cout << *ptr << endl; // the value of sample will be printed
// point to the next location
ptr++;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment