【问题标题】:typecast struct pointer into char pointer reference将结构指针类型转换为 char 指针引用
【发布时间】: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。我不知道限制。您能否给我一些例子或指出一些参考资料。感谢您的帮助。

标签: c++ pointers struct compiler-errors typecasting-operator


【解决方案1】:

函数声明应该是:

err_t call_test_fun(char * data);

你有一个错误的 & 。函数定义应该匹配。

请注意,您的代码使用不属于标准 C++ 的技术:在结构中具有大小为零的数组,并直接写入 malloc 的空间。也许您正在使用带有这些东西作为扩展的编译器,但许多人会因为容易出错而皱眉。毫无疑问,有更好的方法来做你想做的任何事情。

【讨论】:

  • 当然感谢@M.M.我不想删除引用运算符,因为这个函数在很多地方都会被调用。
  • @mehtame026 然后你可以写:char *temp = (char *)x_p; call_test_fun(temp);
  • 知道了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 2017-02-12
  • 2016-05-05
  • 2021-09-20
  • 1970-01-01
相关资源
最近更新 更多