Skip to content

Instantly share code, notes, and snippets.

@goldbattle
Created October 31, 2017 14:49
Show Gist options
  • Select an option

  • Save goldbattle/d2d8b8a684a20adf284d26b1870f7266 to your computer and use it in GitHub Desktop.

Select an option

Save goldbattle/d2d8b8a684a20adf284d26b1870f7266 to your computer and use it in GitHub Desktop.
Simple example of how pointers work when passing into a function.
#include <cstdio>
/**
* This function has a local reference to a pointer
* Thus the memory address of the pointer is different
* But the value the pointer contains remains the same
*/
void function(double* ptrlocal) {
printf("ptr = %p [function ptr address]\n", &ptrlocal);
printf("ptr = %p [function ptr held]\n", ptrlocal);
printf("ptr = %f [function val]\n", *ptrlocal);
}
/**
* This creates a double array and make a pointer to the first row
* We print out:
* 1) the address of the pointer
* 2) value the pointer holds
* 3) data that the pointer points to
*/
int main() {
// Make our data
double arr[4][4];
arr[1][0] = 10;
// Make a pointer
double* ptr = arr[1];
// Print pointer out
printf("ptr = %p [main ptr address]\n", &ptr);
printf("ptr = %p [main ptr held]\n", ptr);
printf("ptr = %f [main val]\n\n", *ptr);
// Pass to the function
function(ptr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment