Hey everybody ! I am a beginner programmer and need some help with pointers. This is what I am trying to do: I have two pointer arguments to a function(caller), say arg1 and arg2. Now I want to manipulate these pointers inside some other function, say func, such that change reflects in the caller from where the func was called. However right now the change I make in the function gets undone in the calling function. Here is the source code:
func(node* arg1, node* argv2)
{
node* point3 = (struct node*) malloc(struct node);
arg2 = arg1;
arg 1 = point3;
}
caller(node* argv1, node* argv2)
{
func(arg1, arg2);
}
Now I know that this can be done using pass by reference technique. But for that func becomes func(node** arg, node** arg2) and I dont want to get into double pointers. I was thinking more on the lines of how an array when manipulated or changed in a function changes for all the functions in the program. Please help me out !
There are two ways to do it:
1) Swap pointers, for this you need to use double pointers(
**)2) Swap content, I think you can do it like this:
Method #1 is more efficient since it will swap pointers instead of whole struct. And as someone mentioned, you should use
sizeof()inside malloc.