& ptr.member和&(ptr.member)之间的差异

时间:2017-07-03 20:06:11

标签: c arrays pointers struct

我正在编写一个c程序,我不太确定如何将数据写入结构的特定成员。我正在使用一个结构指针,它使用realloc()获取已分配的内存,并访问类似于数组的数据。每次添加元素时都会动态调整数组大小。

我的问题是在将数据写入数组索引时,正确的方法是什么?

struct s{...some data members...}
struct s *s_array = NULL;

//allocate memory at some point using realloc()

printf("enter some data: ");
scanf("%d", &s[index].data_member);

OR

scanf("%d", &(s[index].data_member));

1 个答案:

答案 0 :(得分:4)

数组索引运算符[]和成员访问运算符.的优先级都高于地址运算符&

所以&s[index].data_member对于获取数组元素成员的地址是有效的。 &(s[index].data_member)中的括号是多余的,不需要。