将指针(字符串)向下传递给函数的方法

时间:2016-11-21 12:49:01

标签: c pointers

我有一些dillema。我想在这个例子中编辑函数中的字符串。我的问题是在下降时使用***** ptr感觉很奇怪。有没有办法以更“正确的方式”这样做?

的伪代码:

// 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;
}

祝你好运, voodoo16。

1 个答案:

答案 0 :(得分:2)

每次都不需要添加新的间接级别,只需将指针传递给下一个函数即可。

你想要这个:

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 arbitrary length for test purposes
  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;
}