[英]Basic struct question C
for example: 例如:
typedef struct {
int num;
int den;
} rational_number;
rational_number a
; 有理数
a
;
What is the difference between using a.num
or a.den
使用
a.num
或a.den
什么区别
and 和
a->num
or a->den
a->num
或a->den
Thx in advance. 提前谢谢。
->
is for accessing the members of a pointer to a struct, whereas .
->
用于访问指向结构的指针的成员,而.
is for accessing members of the struct itself. 用于访问结构本身的成员。
a->num
is really just shorthand for (*a).num
. a->num
实际上只是(*a).num
。 Example: 例:
typedef struct {
int num;
int den;
} rational_number;
rational_number a;
r.num = 1;
rational_number *a_ptr = &a;
a_ptr->num = 2; /* a.num is now 2 */
you use a.num, when it is normal variable, and a->num when it is pointer 当它是普通变量时,使用a.num;当它是指针时,则使用a-> num
For ex. 对于前。
rational_number a;
a.num; // is correct
a->num; // is wrong
rational_number *b;
b.num;// wrong
b->num; //is correct
The difference is that in the first case you access the structure via a stack variable: 区别在于,在第一种情况下,您可以通过堆栈变量访问结构:
rational_number a;
a.num = 1;
a.den = 1;
in the second case via a heap pointer: 在第二种情况下,通过堆指针:
rational_number* a = new rational_number();
a->num = 1;
a->den = 1;
If a were declared as a pointer to your structure, a->num would return the value of num. 如果将a声明为指向您的结构的指针,则a-> num将返回num的值。
rational_number *a;
a->num = 5;
int new_a;
new_a = a->num;
You have a is declared as a structure, so you should use a.num to return the value of num. 您已将a声明为结构,因此应使用a.num返回num的值。
rational_number a;
a.num = 5;
int new_a;
new_a = a.num;
Both set the value of new_a to 5. 两者都将new_a的值设置为5。
Also, you can get the address of a if it is a structure and use it like a pointer. 另外,如果它是结构,则可以获取它的地址,并将其用作指针。
rational_number a;
(&a)->num = 5;
int new_a;
new_a = a.num;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.