function that returns a pointer in c

int* address_ofInt(int a) {

This is called “passing by value” in C++. This means that whatever the caller passes, as a parameter to the function, effectively a copy is made, and that’s what this a is. This function can modify this a, and it will have no effect on the original parameter, since it’s just a copy.

This a is a completely independent object or variable, and its address is completely different and has nothing to do with the address of whatever was passed to this function.

 return &a;

This function returns the address of its by-value parameter. Which is completely meaningless, since once the function returns its by-value parameter no longer exist. It was a copy of the original parameter that was passed to this function, and it gets automatically destroyed. It is no more. It ceased to be. It joined the choir invisible. It’s pining for the fjords. It is an ex-variable. The caller gets a pointer to a destroyed object, and attempting to dereference the pointer results in undefined behavior.

Your C++ textbook will have a chapter that explains what references are, how they work in C++, and how to pass parameters to the function by reference instead of by value. And in that case modifying a will actually modify the original object that was the parameter to this function. If you do that you will discover that both pointers will be the same, since the function parameter will be a reference to the original parameter that was passed to it. See your C++ textbook for more information.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top