简体   繁体   中英

Casting a void pointer to a struct and initialise it

Casting a void pointer to a struct, i want to initialise the struct component. i used the code below . i want to initialise and access test->args structure. How can i do it?

#include <string.h>
#include <stdio.h>
#include<stdlib.h>
struct ctx {
    int a;
    int b;
    void *args;
  };
struct current_args {
    char *a;
    int b;   
  };


int main()
{
    struct ctx current_ctx = {0};
    struct ctx *test=&current_ctx ;
    struct current_args *args = (struct current_args *)(test->args); 
    args->a=strdup("test");
    args->b=5;
    printf("%d \n", (test->args->b));
    return 0;
}

There is some problem for code snippet as below: actually, test->args is a NULL, it pointers to nothing. Then args->a will cause error like segmentation fault.

struct current_args *args = (struct current_args *)(test->args);//NULL  
args->a=strdup("test"); 

To initialise and access test->args structure, we need add a struct current_args instance, and assign it to test->args ,such as

int main()
{
    struct ctx current_ctx = {0};
    struct ctx *test=&current_ctx ;

    struct current_args cur_args= {0};//added
    test->args = &cur_args;//added

    struct current_args *args = (struct current_args *)(test->args);
    args->a=strdup("test");
    args->b=5;
    printf("%d \n", (((struct current_args*)(test->args))->b));
    return 0;
}

I think you mean the following

struct ctx current_ctx = { .args = malloc( sizeof( struct current_args ) ) };
struct ctx *test = &current_ctx ;

struct current_args *args = ( struct current_args * )( test->args ); 
args->a = strdup( "test" );
args->b = 5;

printf( "%d \n", ( ( struct current_args * )test->args )->b );

//...

free( current_ctx.args );

If your compiler does not support the initialization like this

struct ctx current_ctx = { .args = malloc( sizeof( struct current_args ) ) };

then you can substitute this statement for these two

struct ctx current_ctx = { 0 };
current_ctx.args = malloc( sizeof( struct current_args ) );

You did not properly initialize your struct instance.

struct ctx current_ctx = {0}; sets all members of current_ctx to 0, so the struct is empty and the args pointer is invalid.

You need to first create an args instance and let current_ctx.args point to it like so:

struct args current_args = {a = "", b = 0};
struct ctx current_ctx = {a = 0, b = 0, args = &current_args};

Just remember: Whenever you want to access a pointer, make sure that you have initialized it before.

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