1

私のサンプルプログラムは以下です。

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
}

私の実際の必要性:

  1. void* は function1 に割り当てる必要があります
  2. function2 と function3 に渡す必要があります
  3. function3 のみにメモリを割り当てる必要があります。
  4. データは function2 と function3 でアクセスする必要があります

これを行う方法を教えてください。

ありがとう、ブーベッシュ

4

1 に答える 1

0

OP は相反するニーズを表明するdata

ではfunction1()data「 voidへのポインタへのポインタ」です。
それでもfunction3()OPでは、「...データdata用に100バイト」になりたいと考えています。

より典型的なパラダイムはdatafunction1()

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

dataこの場合、 inのメモリ割り当ては次のようになりますfunction3()

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
  }
}
于 2013-10-19T19:16:08.283 に答える