1

I am new to C/ C++.

I was going through some of the coding questions related to trees and came across this double pointer notation. Can we do the same things using single pointer as first argument in the below function as we can do with double pointers.

void operate(struct Node *root, struct Node **head_ref){ //do something}
Evan Carslake
  • 2,267
  • 15
  • 38
  • 56
sean
  • 146
  • 2
  • 9

3 Answers3

3

There are two ways of interpreting a pointer; a reference to something, or an array. Considering this is a tree, this is probably the first: a reference to another pointer.

Every argument to a function in C is passed by value, which means that if you change the pointer inside the function, it won't be changed outside. To guarantee it is also changed outside, you can use a reference to the pointer: double pointers. You can consider the following example.

void function(int a) {
    a = 5;
}

Even if a is changed above, it is not changed outside of the function. But in this other case,

void function(int * a) {
    *a = 5;
}

the value a is changed outside the function as well. The same thought process can be applied to a pointer(which is also a value).

Charles Welton
  • 841
  • 7
  • 14
0

When you want a function to take care of malloc, free is the main reason.

This is useful if you want to encapsulate memory allocation.

For example some init(struct some_struct **), free(struct some_struct **). And let functions take care of malloc, free. Instead of allocating on stack.

For example a function that packs a string of unknown length.

   size_t pack_struct(char** data, const struct some_struct * some_struct)
   {
   /**
    * @brief buffer
    * @note verify the needed buffer length
    */
   char buffer [256]; // temporary buffer

   *data = 0;

   //const char* package_pattern = "%cW ;%u.%u;%s%c";
   size_t len = sprintf(buffer,  weight_package_pattern,
                    START_CHARACTER,                    
                    some_struct->ts.tv_sec,
                    some_struct->ts.tv_usec,
                    some_struct->string_of_unknown_length, // but no more then buffer
                    STOP_CHARACTER);

  if(len == 0) {
    perror("sprintf failed!\n");
    return len;
   }

  // len++; // for end character if wanna some, see sprintf description

  *data = (char*)malloc(len*sizeof(char)); // memory allocation !
  strncpy(*data, buffer, len);

  return len;
}

However such technic should be avoided when programming in C++.

Maquefel
  • 480
  • 4
  • 16
0

Double pointer is normally used when allocating memory.

#include <stdlib.h>
void new_malloc(void **p, size_t s) {
    *p = malloc(s);
    /* do something */
}

int main() {
  int *p;
  new_malloc((void **)&p, sizeof(int) * 10);
}
tele
  • 11
  • 2