如何使用指向该数组的指针访问结构数组中包含的结构中的字段? [C ++]

时间:2018-01-25 18:41:06

标签: c++ arrays pointers struct

我想使用排序算法按结构中包含的某个字段中的值对结构数组进行排序。让我用一个例子来更好地说明我的观点。

struct person{
    string name;
    int height;
}

person people[10];
person *ptr = people;

基本上,使用这个例子,我想要使用ptr按照数组中人员的高度对数组进行排序。

我对指针很新,所以他们仍然混淆了我,我一直无法弄清楚如何轻松访问特定结构中的高度字段而不使用ptr ++然后ptr-> height,这是如果我想比较数组中两个独立结构的高度,那就没用了。我不确定这是否可能

我知道要访问您将使用的数组中的值

*(ptr + [int]);

但这似乎不能用于访问结构中包含的值。以下是我尝试使用的方法

*(ptr + [int]).height;
*(ptr + [int])->height;
*(ptr.height + [int]);

这些都不起作用,而且我试图研究解决方案,但我已经做得不够了。任何能指向正确方向的东西都会受到赞赏。提前谢谢!

2 个答案:

答案 0 :(得分:1)

int index = 0;
ptr[index].name;
ptr[index].height;

答案 1 :(得分:0)

如果我理解正确,您希望使用指针访问数组的元素。在这种情况下,像ptr[i].height这样简单的工作。这是一个完整的工作示例

#include <iostream>
#include <string>

struct person{
    std::string name;
    int height;
};

int main()
{
  person people[10];
  for (int i=0; i<10; i++)
  {
      people[i].height = i;
  }

  person *ptr = people;

  for (int i=0; i<10; i++)
  {
      std::cout << ptr[i].height << std::endl;
  }

}