我试图通过一个常量结构来改变一个整型变量,一个指向其他结构的指针,其中一个字段就是这个变量。我在编译过程中得到一个警告和一个错误。任何人都可以解释为什么以及如何使用这段代码?
代码是:
typedef struct
{
struct TEEC_Session *ptr_struct;
} Context_model;
typedef struct
{ int t_S;
} Session_model;
void Attribution(Context_model* context,Session_model* session )
{
(*context).ptr_struct = session;
}
void change_t_S(Context_model* context )
{
(*(*context).ptr_struct).t_S = 5; // I Want to change t_S to 5 using only the
context structure
}
main()
{
Context_model context;
Session_model session;
Attribution(&context,&session);
// Now I want to change t_S using the context
change_t_S(&context);
}发布于 2012-07-27 00:42:46
将Context_model的定义修改为
typedef struct
{
Session_model *ptr_struct;
} Context_model;并将其移动到Session_model的定义之下。
您的代码中未定义结构TEEC_Session。
发布于 2012-07-27 00:47:07
您正在声明您的ptr_struct具有struct TEEC_Session *类型,但随后却试图将其用作Session_model *类型的指针。这是一个明显的类型不匹配。这根本就说不通。
什么是struct TEEC_Session?在您的整个程序中没有提到TEEC_Session。为什么要将ptr_struct字段声明为指向某种完全随机的非常规类型struct TEEC_Session的指针,然后完全忘记该struct TEEC_Session的存在呢
如果您的struct TEEC_Session类型被认为是Session_model类型的同义词,那么您应该告诉编译器这一点。例如,您可以将Session_model声明为
typedef struct TEEC_Session
{
int t_S;
} Session_model;一切都会像预期的那样工作。
或者,您可以通过重新排序声明来完全消除对TEEC_Session的任何引用
typedef struct
{
int t_S;
} Session_model;
typedef struct
{
Session_model *ptr_struct;
} Context_model;最后,在代码中使用C99样式的注释(//)。C99不允许声明没有显式返回类型的函数。main()应为int main()。
发布于 2012-07-27 00:58:54
我展示了带有附加声明和指针取消引用习惯用法的代码。
这段代码在C,HTH中编译正常。
struct TEEC_Session;
typedef struct
{ struct TEEC_Session *ptr_struct;
} Context_model;
typedef struct TEEC_Session
{ int t_S;
} Session_model;
void Attribution(Context_model* context,Session_model* session )
{
context->ptr_struct = session;
}
void change_t_S(Context_model* context )
{
context->ptr_struct->t_S = 5; // I Want to change t_S to 5 using only the context structure
}
int main_change_var(int argc, char **argv)
{
Context_model context;
Session_model session;
Attribution(&context,&session);
// Now I want to change t_S using the context
change_t_S(&context);
return 0;
}https://stackoverflow.com/questions/11671695
复制相似问题