[英]Typedef struct pointers
I want to pass a pointer to my struct into a function to edit the struct. 我想将指向我的结构的指针传递给函数以编辑该结构。
This does not work: 这不起作用:
typedef struct{
unsigned char x;
unsigned char y;
float z;
}C_TypeDef;
C_TypeDef *ptr_struct; //This is the part that I change to get it to work.
void print_TypeDef(C_TypeDef *report, unsigned char x_data)
{
report->x = x_data;
printf("x is equal to %d", report->x);
}
int main(void)
{
print_TypeDef(ptr_struct,0x23);
getchar();
}
Now if I change the part that I declare the pointer to this is still does not work. 现在,如果我更改了声明指向该指针的部分仍然无法正常工作。 This does not work:
这不起作用:
C_TypeDef x_struct;
C_TypeDef *ptr_struct;
ptr_struct = &x_struct;
But if I change it to this, it does work!! 但是,如果我将其更改为此,它将起作用!!
C_TypeDef x_struct;
C_TypeDef *ptr_struct = &x_struct;
My question is why don't the first two work? 我的问题是为什么前两个不起作用? This is bugging me.
这使我烦恼。
The problem of the first version is, you didn't allocate memory for what ptr_struct
points to, it usually leads to segmentation fault. 第一个版本的问题是,您没有为
ptr_struct
指向的内存分配内存,这通常会导致分段错误。 This is fixed in: 此问题已修复:
C_TypeDef x_struct;
C_TypeDef *ptr_struct = &x_struct;
That's why the third version works. 这就是第三个版本起作用的原因。 Then what's wrong with the second version?
那第二版怎么了? Because you can't assign a global variable outside any functions, you can initialize them like what you did in the third version, or you should assign it in some function, like in
main
: 因为您不能在任何函数外部分配全局变量,所以可以像在第三版中那样初始化它们,或者应该在某些函数中对其进行分配,例如在
main
:
C_TypeDef x_struct;
C_TypeDef *ptr_struct;
//omit other parts
int main(void)
{
ptr_struct = &x_struct; //Here assign the pointer a value
print_TypeDef(ptr_struct,0x23);
getchar();
}
The first version of code is not working because you have created a pointer type to the structure, and not really assigned any address. 代码的第一个版本不起作用,因为您已经创建了指向该结构的指针类型,并且没有真正分配任何地址。 But trying to access it in the calling function
但是尝试在调用函数中访问它
print_TypeDef(ptr_struct,0x23);\\here ptr_struct is not pointing to any instance of the structure.
The second version is not working because the statements 第二个版本不起作用,因为以下语句
C_TypeDef x_struct;
C_TypeDef *ptr_struct;
is perfectly correct, but the next statement of assigning a value to an variable is not at all possible outside of any function. 是完全正确的,但是下一个将值赋给变量的语句根本不可能在任何函数之外进行。
C_TypeDef x_struct;\\correct, creating a instance of struct type
C_TypeDef *ptr_struct;\\correct, creating a pointer to an structure
ptr_struct = &x_struct;\\wrong, as this statement is possible only inside a function.
Incidentally for your code to work you need not create both the structure instance and a pointer of that instance, instead it will work well by 顺便说一句,为了使代码正常工作,您无需同时创建结构实例和该实例的指针,而是可以很好地工作
C_TypeDef x_struct;
and in main, call the function like this, 总的来说,这样调用函数
int main(void)
{
print_TypeDef(&x_struct,0x23);
getchar();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.