gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:47:32 25 4
gpt4 key购买 nike

我的示例程序如下。

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中访问

你能帮我看看怎么做吗?

谢谢,嘘声

最佳答案

OP 表达了对data

的冲突需求

function1() 中,data 是一个“指向 void 指针的指针”。
然而在 function3() 中,OP 希望 data 为“... 100 字节用于 data”。

一个比较典型的范式是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;
}

那么在这种情况下,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
}
}

关于c - 如何为双指针分配内存并且它应该在 f1、f2 和 f3 中可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19469098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com