Search code examples
c++pointersstructcompiler-errorstypecasting-operator

typecast struct pointer into char pointer reference


Is it possible to typecast struct pointer into char pointer reference? I know that we can cast any pointer type to any other pointer type. But I got an error when I tried to typecast structure. I am using C++ compiler.

Error :
error: invalid initialization of non-const reference of type 'char*&' from a temporary of type 'char*'

Please see below example:

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);

Solution

  • The function declaration should be:

    err_t call_test_fun(char * data);
    

    you had an erroneous & . The function definition should match.

    Note that your code uses techniques that are not part of Standard C++: having a zero-sized array in a struct, and writing directly into malloc'd space. Maybe you are using a compiler with those things as extensions but it will be frowned on by many people as being prone to error. There is undoubtedly a better way to do whatever it is you are trying to do.