Sunday 10 June 2018

c++ - Pointers passed by reference? (Sanity check)

I am conceptually confused about what I am seeing in following situation: a pointer is passed from main() to function ( func1() ) by reference. func1() then further passes this pointer to func2() also by reference. Now if func2() updates the pointer so that it now points to a new address, this reflects back in main().




Doubts:



1. Is it some sort of pointer-to-pointer-to-pointer in the background?



2. Isn't the reference *&ptr1 and *&ptr2 in func1() being initialized to NULL when ptr1 and ptr2 are passed by reference in main() ? I had read that references cannot be initialized to NULL.



#include 
using namespace std;

void func2(int *&ptr2)

{
int var2 = 123;
ptr2 = &var2;

cout << endl <<"func2 - ptr2: " << ptr2 << endl;
}

void func1(int *&ptr1, int *&ptr2)
{
int var1 = 111;

ptr1 = &var1;
func2(ptr2);

cout << endl << "func1 - ptr1: " << ptr1 << " ptr2: " << ptr2 << endl;
}

int main()
{
int *ptr1 = NULL;
int *ptr2 = NULL;

cout << "main - ptr1: " << ptr1 << " ptr2: " << ptr2 << endl;

func1(ptr1, ptr2);
cout << "main now - ptr1: " << ptr1 << " ptr2: " << ptr2 << endl;

return 0;
}


OUTPUT:




main - ptr1: 0  ptr2: 0

func2 - ptr2: 0x28fe3c

func1 - ptr1: 0x28fe6c ptr2: 0x28fe3c
main now - ptr1: 0x28fe6c ptr2: 0x28fe3c

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...