Hi all, in below test code, if I pass a NULL pointer to the add(int*) function, I still couldn't get the allocated space in my main function. And it thus gave me segmentation fault.
Could you advise why? A workaround for this issue would be pass by a reference of a point, eg,
Your function header is different than what you list.
void add(int* &i)
This is a reference to a pointer-to-int.
void add(int* i)
This is just a pointer-to-int (which is passed by value).
Hence, your function cannot modify the i in main() (declared on line 17). If you fix your add() function to take the proper type of argument, it will work.
You should also remember to delete i; before you return 0;.
One last thing: The name "add" is not properly informative. Use "increment" or "inc" or "incr" or "bump" etc.
Hi Duoas, your reply is very helpful. Thanks. So what you mean is the function cannot modify i (the pointer itself) in main(). However if I pass a non-NULL pointer, and I can get the updated value pointed by i.
Maybe I mixed two concepts here, the pointer itself and the value pointed by the pointer? Thanks.
...which is what he intended, of course. The problem is that he is confused by combining the ideas between pointers and references and the redirections complicit in each...