简体   繁体   中英

How to cast a pointer to void which is nested in a struct?

This example is made up for demonstration, but I need to cast the pointer as in the example

I am getting the following errors:

test2.c: In function ‘main’:
test2.c:25:12: error: expected identifier before ‘(’ token
test2.c:25:12: error: too few arguments to function ‘strcpy’
test2.c:26:20: error: expected identifier before ‘(’ token

The code is this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test {
        void *ptr;
        char str[300];
};
struct test2 {
        int i;
        char astr[200];
};

int main(void)
{
        struct test *p;
        p = malloc(sizeof(struct test));
        p->ptr = malloc(sizeof(struct test2));
        /*
        void *p2;
        p2 = p->ptr;
        strcpy(((struct test2 *)p2)->astr, "hello world");
        printf("%s\n", ((struct test2 *)p2)->astr);
        */
        strcpy(p->(struct test2 *)ptr->astr, "hello world");
        printf("%s\n", p->(struct test2 *)ptr->astr);
        return 0;
}

The commented-out part of the code works well. I understand that the processor can not dereference the pointer without additional variable and the compiler will create an additional variable, but I want to understand how to cast the pointer that is nested in the structure without creating an additional variable?

Just to make the code look more compact, I will often use a similar thing and I'd like to write it in one line without additional variables.

C++ variant:

strcpy(reinterpret_cast<struct test2 *>(p->ptr)->astr, "hello world");

Also it is worth pointing out, that strcpy function is unsafe and should not be used. Use strcpy_s instead.

You need to apply -> to the result of the cast (notice the parentheses around the entire cast expression):

strcpy(((struct test2 *)(p->ptr))->astr, "hello world");
printf("%s\n", ((struct test2 *)(p->ptr))->astr);

Live example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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