2015-07-11 46 views
1

将一个void指针投射到一个结构上,我想初始化结构组件。我使用下面的代码。 我想初始化并访问test-> args结构。我该怎么做?将一个void指针投射到一个结构并初始化它

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

什么是你的问题? – haccks

+3

那么,你*做*指针,但它已经初始化为'NULL',所以取消引用它是未定义的。 – EOF

回答

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

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

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

您需要先创建args中,该实例,让current_ctx.args指向它,像这样:

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

只要记住:当你要访问的指针,请确保您之前初始化它。

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)); 
相关问题