显示传递的Struct数据

时间:2013-10-03 07:00:33

标签: c pointers struct

说,给定结构:

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

3 个答案:

答案 0 :(得分:1)

您正在使用cmd进行打印。将 cmd 的类型更改为struct someStruct *或输入类型。

void指针没有类型,因此不知道如何执行指针算法来访问所需的字段。

答案 1 :(得分:0)

您需要将cmd强制转换为someStruct:

((struct someStruct*)cmd)->total

答案 2 :(得分:-1)

你应该使用

cmd_ptr = &s;

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

becuse cmd是无效指针,除非你将它强制转换为someStruct,否则它无法显示