Reputation: 507
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=¤t_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;
}
Upvotes: 1
Views: 380
Reputation: 1924
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=¤t_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;
}
Upvotes: 1
Reputation: 310940
I think you mean the following
struct ctx current_ctx = { .args = malloc( sizeof( struct current_args ) ) };
struct ctx *test = ¤t_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 ) );
Upvotes: 1
Reputation: 3354
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 = ¤t_args};
Just remember: Whenever you want to access a pointer, make sure that you have initialized it before.
Upvotes: 0