[英]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: 我的实际需要:
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.