簡體   English   中英

將void指針轉換為結構並對其進行初始化

[英]Casting a void pointer to a struct and initialise it

鑄造指向結構的空指針,我想初始化結構組件。 我用下面的代碼。 我想初始化並訪問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;
}

如下代碼段存在一些問題:實際上, 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;
}

我想你是說以下

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

您沒有正確初始化結構實例。

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

只需記住:每當您要訪問指針時,請確保之前已對其進行了初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM