【发布时间】:2017-04-26 01:04:58
【问题描述】:
是否可以将 struct 指针类型转换为 char 指针引用?我知道我们可以将任何指针类型转换为任何其他指针类型。但是当我尝试对结构进行类型转换时出现错误。我正在使用 C++ 编译器。
错误:
错误:从 'char*' 类型的临时变量中对 'char*&' 类型的非常量引用的初始化无效
请看下面的例子:
struct test {
int a;
bool y;
char buf[0];
}
struct test *x_p = NULL;
char *p = "Some random data......"; // this can be more than 64 bytes
x_p = (struct test *) malloc(sizeof(struct test) + 65);
x_p->a = 10;
x_p->y = false;
memcpy(x_p->buf, p, 64); //copy first 64 bytes
/* Here I am getting an error :
* error: invalid initialization of non-const reference of type 'char*&' from a temporary of type 'char*'
*/
call_test_fun((char *)x_p);
// Function Declaration
err_t call_test_fun(char *& data);
【问题讨论】:
-
错误信息只能由 C++ 编译器生成,但您已标记问题 C。C 和 C++ 是不同的语言。请决定您要使用哪种语言;然后为该语言使用正确的编译器并选择相应的标签,[c] 或 [c++] 但不能同时选择两者。
-
"知道我们可以将任何指针类型转换为任何其他指针类型。" --> 不,有限制。
-
感谢@M.M 和 chux 的及时回复。对不起,我正在使用 C++ 编译器。我会更新问题。
-
对不起@chux。我不知道限制。您能否给我一些例子或指出一些参考资料。感谢您的帮助。
-
@mehtame026 stackoverflow.com/q/17260527/2410359
标签: c++ pointers struct compiler-errors typecasting-operator