Created
December 28, 2016 15:35
-
-
Save ashwin/6ae52a0712e905977185af76ba48e374 to your computer and use it in GitHub Desktop.
Example showing difference between pointer-to-pointer and reference-to-pointer in C++
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
// Example that shows difference between pointer-to-pointer | |
// and reference-to-pointer. | |
#include <cstdio> | |
void func_ptr(int **x) | |
{ | |
*x = new int; | |
**x = 100; | |
} | |
void func_ref(int * &x) | |
{ | |
x = new int; | |
*x = 99; | |
} | |
int main() | |
{ | |
// Pointer-to-pointer | |
{ | |
int *xp = nullptr; | |
func_ptr(&xp); | |
printf("%d\n", *xp); | |
delete xp; | |
} | |
// Reference-to-pointer | |
{ | |
int *xp = nullptr; | |
func_ref(xp); | |
printf("%d\n", *xp); | |
delete xp; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment