Fahad
Fahad

Reputation: 95

Pointer Manipulation in C

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 !

Upvotes: 0

Views: 815

Answers (4)

Bart
Bart

Reputation: 1653

As others said, using pointers to pointers in this case is how it's done in C. There is however a possibility to avoid this: use macros....

#define func(arg1, argv2) do { node * point3 = malloc(); /* etc ... */ } while(0)

But your code is not gonna be more beautiful by doing to that. Don't be tempted by the dark side of C.

Upvotes: 0

Dave Costa
Dave Costa

Reputation: 48121

Doing the double pointer is really the right way to do it. But if you find that confusing, you could pass an array of two pointers to the function instead. Then the contents of the array would be modified upon return.

Upvotes: 0

Caner
Caner

Reputation: 59178

There are two ways to do it:
1) Swap pointers, for this you need to use double pointers(**)


func(node** arg1, node** arg2)
{
  node* tmp = *arg2;
  *arg2 = *arg1;
  *arg1  = tmp;
}

2) Swap content, I think you can do it like this:


func(node* arg1, node* arg2)
{
  node* tmp = (struct node*) malloc(sizeof(struct node));
  node* clean = tmp; 
  *tmp = *arg2;
  *arg2 = *arg1;
  *arg1  = *tmp;
  free(clean);
}

Method #1 is more efficient since it will swap pointers instead of whole struct. And as someone mentioned, you should use sizeof() inside malloc.

Upvotes: 1

Šimon Tóth
Šimon Tóth

Reputation: 36433

If you want to modify the pointers themselves, you need to pass pointer to pointer. Therefore func(node** arg1, node** arg2) is correct.

Upvotes: 0

Related Questions