簡體   English   中英

顯示來自Struct的數據傳遞

[英]Displaying data from Struct being passed around

說,給定的結構:

struct someStruct {
 unsigned int total;
};

struct someStruct s;    // initiate an instance (allocate memory)   
s.total = 5555;                   // set a value

// and for    
void* cmd;       // local holder, which is a pointer (may be an argument of a function)


// at some given time
// format the designated pointer with a struct form(at), 'casting' the pointer
struct someStruct *cmd_ptr = (struct someStruct *) cmd;
cmd = &s;      // pass the specific address of the allocated structure and space to the pointer

我們如何顯示cmd.total值? 這些都不起作用。

// retrieve the data    
//printf(" Struct contents: %d \n", (cmd->total)); // use designated pointer
//printf(" Struct contents: %d \n", (*cmd).total);  // use designated pointer
//printf(" Struct contents: %d \n", cmd.total); // use specific address
//printf(" Struct contents: %d \n", (&cmd).total);  // use designated pointer
//printf(" Struct contents: %d \n", (&cmd)->total);  // use designated pointer

您正在使用cmd進行打印。 更改cmd的類型以struct someStruct *struct someStruct *類型轉換。

void指針沒有類型,因此不知道如何執行指針算法來訪問必填字段。

您需要將cmd投射回someStruct:

((struct someStruct*)cmd)->total

你應該用

cmd_ptr = &s;

printf(" Struct contents: %d \\n", (cmd_ptr->total));

因為cmd是void指針,除非將其鍵入到someStruct中,否則它不會顯示

暫無
暫無

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

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