简体   繁体   English

c ++指向结构数组的指针

[英]c++ pointer to array of structs

Can someone please explain to me why this doesn't work?有人可以向我解释为什么这不起作用吗?

struct person {
  string name;
  int age;
};

// in function
person friends[NUM_OF_FRIENDS];
friends[0].name = "bob";
friends[1].name = "bill";
friends[2].name = "liz";
friends[3].name = "frank";
friends[4].name = "carl";
friends[0].age = 20;
friends[1].age = 30;
friends[2].age = 32;
friends[3].age = 10;
friends[4].age = 85;

// array of pointers

person (*friends_ptrs)[NUM_OF_FRIENDS] = &friends;

cout << friends_ptrs[0]->name << endl;

cout << friends_ptrs[1]->name << endl;

"bob" is printed fine, but "bill" causes an error. “bob”打印得很好,但“bill”会导致错误。 How can "bob" print at all while "bill" is not found?在找不到“账单”的情况下,“鲍勃”如何打印?

I realize that I can just do this:我意识到我可以这样做:

person *friends_ptrs = friends;

But then I'm not using the arrow notation, and it defeats the purpose of this exercise.但是我没有使用箭头符号,它违背了这个练习的目的。

So how can I access the friends[] struct, using a pointer with arrow notation?那么如何使用带有箭头符号的指针访问朋友 [] 结构呢?

You've created a pointer to an array, not an array of pointers.您创建了一个指向数组的指针,而不是一个指针数组。

So, this will work:所以,这将起作用:

cout << (*friends_ptrs)[1].name << endl;

If you want an array of pointers, write:如果你想要一个指针数组,写:

person* friends_ptrs[NUM_OF_FRIENDS];

friends_ptrs[0] = &friends[0];
friends_ptrs[1] = &friends[1];
// ...

I don't understand what exactly you are trying to do.我不明白你到底想做什么。 If you want to get an array of pointers from your array of structs, you will need to make a loop.如果要从结构数组中获取指针数组,则需要进行循环。 It would look like this (i did not try it)它看起来像这样(我没有尝试过)

person * friends_ptrs[NUM_OF_FRIENDS];
for (int i = 0; i < NUM_OF_FRIENDS; i++)
    friends_ptrs[i] = friends + i;

first thing that you must know is that name of array is address of first node of array,so when you must change this line :您必须知道的第一件事是数组的名称是数组的第一个节点的地址,因此当您必须更改此行时:

person (*friends_ptrs)[NUM_OF_FRIENDS] = &friends;

to

person* friends_ptrs = friends;

tow,in above line you ought not create an array of pointers.拖曳,在上面的行中,您不应该创建指针数组。

friends is a pointer to the first element in array.朋友是指向数组中第一个元素的指针。 Using pointer arithmetic you can use the arrow notation in following way:使用指针算法,您可以按以下方式使用箭头符号:

cout << friends->name;
cout << (friends++)->name; //Incrementing it will give you the pointer to second one.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM