D Walters
D Walters

Reputation: 13

How to access a field in a struct contained in an array of structs using a pointer to that array? [C++]

I want to use a sorting algorithm to sort the array of structs by the values in one of the fields contained in the struct. Let me use an example to better illustrate my point.

struct person{
    string name;
    int height;
}

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

Essentially, using this example, I would want to sort the array by the heights of the people in the array using ptr.

I am very new to pointers, so they still confuse the heck out of me, and I have been unable to figure out how to easily access the height field in specific structures without using ptr++ then ptr->height, which is not useful if I wanted to compare the heights of two separate structures in the array. I'm not sure if this is even possible.

I know to access values in an array you would use

*(ptr + [int]);

but that doesn't seem to work in accessing values contained in the structures. Here are the methods that I've tried to use

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

None of these work, and I've tried to research a solution, but I've come up short. Anything that would point me in the correct direction would be appreciated. Thank you in advance!

Upvotes: 0

Views: 66

Answers (2)

dvd8719
dvd8719

Reputation: 58

If I understand you correctly, you want to access elements of your array by using the pointer. In this case, something as simple as ptr[i].height works. Here is a full working example

#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;
  }

}

Upvotes: 0

michalsrb
michalsrb

Reputation: 4881

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

Upvotes: 1

Related Questions