[英]pass by reference & assign value to a pointer of pointer of struct
I have a struct MY_TYPE
: 我有一个结构MY_TYPE
:
struct MY_TYPE {
boolean flag;
short int xyz;
};
I have another struct MY_DATA
which has a field with type of pointer to the above struct: 我还有另一个结构MY_DATA
,它的字段类型指向上述结构:
struct MY_DATA {
MY_TYPE *m_type;
double value;
};
I have a function which takes a pointer to pointer of MY_DATA
as parameter: 我有一个函数,该函数将指向 MY_DATA
指针作为参数:
getData(struct MY_DATA **m_data) {
// create a MY_TYPE pointer & assign value to its field
struct MY_TYPE *m_type_tmp = malloc(sizeof(struct MY_TYPE));
m_type_tmp -> xyz = 123;
// I try to assign a value to the MY_TYPE field of m_data,
// there is no compiler error, but run time error "bad access"
(** m_data).m_type = m_type_tmp;
}
I call above function by: 我通过以下方式调用上述函数:
struct MY_DATA *data;
get_data(&data);
The compiler doesn't complain anything, but when run my code, I get "Bad access" on the last line of code of function get_data(...)
, how come? 编译器没有任何抱怨,但是运行我的代码时,我在函数get_data(...)
的最后一行得到“错误访问”,这是怎么回事?
Since you pass the address of an uninitialized pointer, you must allocate the structure MY_DATA
as well: 由于传递了未初始化指针的地址,因此还必须分配结构MY_DATA
:
void getData(struct MY_DATA **m_data) {
// create a MY_TYPE pointer & assign value to its field
struct MY_TYPE *m_type_tmp = malloc(sizeof(struct MY_TYPE));
m_type_tmp->flag = 0;
m_type_tmp->xyz = 123;
// allocate the MY_DATA structure:
*m_data = malloc(sizeof(*m_data));
// Initialize all members
(*m_data)->m_type = m_type_tmp;
(*m_data)->value = 0;
}
It would be simpler to have the function return a pointer to the allocated structure: 让函数返回指向已分配结构的指针会更简单:
struct MY_DATA *getData(void) {
// create a MY_TYPE pointer & assign value to its field
struct MY_TYPE *m_type_tmp = malloc(sizeof(*m_type_tmp));
m_type_tmp->flag = 0;
m_type_tmp->xyz = 123;
// allocate the MY_DATA structure:
struct MY_DATA *m_data = malloc(sizeof(*m_data));
// Initialize all members
m_data->m_type = m_type_tmp;
m_data->value = 0;
return m_data;
}
And invoke it this way: 并以这种方式调用它:
struct MY_DATA *data = get_data();
getData(struct MY_DATA ** m_data) getData(结构MY_DATA ** m_data)
You don't need pointer to pointer to MY_DATA
, pointer to MY_DATA
would be suffice. 你不需要指针指向MY_DATA
,指针MY_DATA
将是足够的。
Then instead of (** m_data).m_type = m_type_tmp;
然后代替(** m_data).m_type = m_type_tmp;
you can write: 你可以写:
m_data->m_type = m_type_tmp;
Also these are incorrect: 这些也不正确:
struct MY_DATA *data; // <-- you haven't initialized the pointer
get_data(&data);
You can fix that by: 您可以通过以下方法解决此问题:
struct MY_DATA data = {0};
get_data(&data);
按引用传递意味着您将值传递给其他变量的引用,而按值传递意味着将值传递给字符串,float,character或boolean。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.