简体   繁体   English

如何为双指针分配内存,并且它应该在f1,f2和f3中可见?

[英]How to allocate memory for double pointer and it should be visible in f1, f2 and f3?

My sample program is below. 我的示例程序如下。

void function1 () {
    void **data
    function2(data);
    //Will access data here
}

void function2(void **data) {
    function3(data);
    //Will access data here
}

void function3(void **data) {
    //Need to allocate memory here says 100 bytes for data
    //Populate some values in data
}

My actual need: 我的实际需要:

  1. void* should be allocated in function1 void *应该在function1中分配
  2. that should be passed across function2 and function3 应该通过function2和function3传递
  3. memory must be allocated in function3 only. 只能在function3中分配内存。
  4. data must be accessed in function2 and function3 必须在功能2和功能3中访问数据

Could you please help me how to do this? 您能帮我怎么做吗?

Thanks, Boobesh 谢谢,Boobesh

OP expresses conflicting needs for data OP表示对data需求冲突

In function1() , data is a " pointer to pointer to void". function1()data是“ 指向 void的指针”。
Yet in function3() OP wants data to be "... 100 bytes for data ". 但是在function3() OP希望data为“ ... 100个字节的数据 ”。

A more typical paradigm is that data in function1() is 一个更典型的范例是function1()中的data

void function1 () {
  void *data = NULL;
  function2(&data);  // Address of data passed, so funciton2() receives a void **
  //Will access data here
  unsigned char *ucp = (unsigned char *) data;
  if ((ucp != NULL) && (ucp[0] == 123)) { 
    ;  // success
  }
  ...
  // Then when done
  free(data);
  data = 0;
}

Then in this case the memory allocation for data in function3() is 那么在这种情况下, function3() data的内存分配为

void function3(void **data) {
  if (data == NULL) {
    return;
  }
  // Need to allocate memory here.  Say 100 bytes for data
  size_t Length = 100;
  *data = malloc(Length);
  if (data != NULL) {
    //Populate some values in data
    memset(*data, 123, Length);
  }
}

void function2(void **data) {
  if (data == NULL) {
    return;
  }
  function3(data);
  unsigned char *ucp = (unsigned char *) *data;
  // Will access data here
  if ((ucp != NULL) &&  (ucp[0] == 123)) { 
    ;  // success
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM