繁体   English   中英

将类型转换结构指针转换为char指针引用

[英]typecast struct pointer into char pointer reference

是否可以将结构指针转换为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);

函数声明应为:

err_t call_test_fun(char * data);

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

请注意,您的代码使用的技术不是标准C ++的一部分:在结构中具有大小为零的数组,并直接写入malloc的空间。 也许您正在使用具有这些扩展功能的编译器,但由于容易出错,因此许多人不赞成它。 毫无疑问,有更好的方法可以完成您要尝试执行的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM