gpt4 book ai didi

c - 如何访问数组中结构的成员?

转载 作者:太空宇宙 更新时间:2023-11-04 00:51:12 25 4
gpt4 key购买 nike

这一定是一个非常简单的问题,我有一个包含四个元素的结构,一个结构变量被初始化为一个数组,现在的问题是我可以访问数组的第一行但我不知道如何访问剩余的行...请指导我!

  //structure is defined as follows      
typedef struct{
char first_name[100];
char second_name[100];
int x_position;
int y_position;
} names;

int main(void)
{
int i=0;
//here i have initilized structure variable
names my_data[] = {
{"First", "Row", 20, 12},
{"Second", "Row", 55, 30},
{"Third", "Row", 80, 47},
{"Fourth", "Row", 27, 34}
};
//trying to acess the diffrent row elements ....but dont know how??
for(i=0; i<=3; i++)
{
printf("%s\n",my_data->first_name);
printf("%s\n",my_data->second_name);
printf("%d\n",my_data->x_position);
printf("%d\n",my_data->y_position);
}
system("PAUSE");
return 0;
}

最佳答案

在循环中正确:

 printf("%s\n", my_data[i].first_name);

注意:precedence [] 数组下标运算符高于 通过对象名称运算符选择成员,因此您不需要 () 括号。

 printf("%s\n",(my_data + i)->first_name);

其次,+ 加运算符的优先级较低,因此我们需要括号来覆盖优先级。

关于c - 如何访问数组中结构的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18329638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com