将void指针强制转换为struct并初始化它

时间:2015-07-11 10:43:28

标签: c

将void指针强制转换为struct,我想初始化struct组件。我使用下面的代码。 我想初始化并访问test-> args结构。我该怎么办?

#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;
}

3 个答案:

答案 0 :(得分:1)

代码片段有一些问题如下:实际上,test->args是NULL,它指向什么都没有。然后args->a会导致分段错误等错误。

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

要初始化和访问test->args结构,我们需要添加struct current_args个实例,并将其分配给test->args,例如

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

答案 1 :(得分:1)

我认为你的意思是以下

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

如果你的编译器不支持这样的初始化

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

然后你可以用这个语句代替这两个

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

答案 2 :(得分:0)

您没有正确初始化结构实例。

struct ctx current_ctx = {0};将current_ctx的所有成员设置为0,因此struct为空,args指针无效。

你需要先创建一个args实例,然后让current_ctx.args指向它:

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

请记住:每当您想要访问指针时,请确保您之前已初始化它。