1

说,给定结构:

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
4

3 回答 3

1

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

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

于 2013-10-03T07:04:33.670 回答
0

您需要转换cmd回 someStruct:

((struct someStruct*)cmd)->total
于 2013-10-03T07:05:06.003 回答
-1

你应该使用

cmd_ptr = &s;

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

因为 cmd 是 void 指针,除非您将其类型转换为 someStruct,否则它无法显示

于 2013-10-03T07:05:21.493 回答