typecast struct指针进入char指针引用

时间:2017-04-26 01:04:58

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

是否可以将struct指针强制转换为char指针引用?我知道我们可以将任何指针类型转换为任何其他指针类型。但是当我试图对结构进行类型转换时,我收到了一个错误。我正在使用C ++编译器。

错误:
    错误:类型' char *&'的非const引用的无效初始化来自临时的#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);

1 个答案:

答案 0 :(得分:0)

函数声明应为:

err_t call_test_fun(char * data);
你有一个错误的&。函数定义应该匹配。

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