voodoo16 voodoo16 - 15 days ago 6
C Question

Way of passing pointer (strings) deep down to functions

I'm having some dillema. I want to edit, in this example, strings in functions. My problem is that using *****ptr when going down feels weird. Is there any way of doing this 'more' proper way?

Pseudo-code:

// all funX return array length
int fun1(int **ptr){
//some READ/WRITE on pointers, like mallocs, giving value etc.
int len = 0;
len = fun2(&ptr);
return len;
}

int fun2(int ***ptr){
// some more READ/WRITE on pointers, like mallocs, giving value etc.
// what about going even deeper?
}

int main(){
int *someString = NULL;
int len = 0;
len = fun1(&someString);
// some string operations
free(someString);
return 1;
}


Best regards,
voodoo16.

Answer

There is no need to add a new level of indirection each time, you simply pass your pointer to the next function.

You want this:

int fun2(int **ptr) {
  // some more READ/WRITE on pointers, like mallocs, giving value etc.
  // what about going even deeper?

  *ptr = (int*)malloc(190);   // 190 is just some arbirary length
  return 190;
}


// all funX return array length
int fun1(int **ptr) {
  //some READ/WRITE on pointers, like mallocs, giving value etc.
  int len = 0;               // BTW you dont need to initialize to 0
  len = fun2(ptr);
  return len;
}


int main() {
  int *someString = NULL;
  int len = 0;               // BTW you dont need to initialize to 0
  len = fun1(&someString);
  // some string operations
  free(someString);
  return 1;
}