C 结构阵列带指针

C++ struct array with pointer

本文关键字:指针 阵列 结构      更新时间:2023-10-16

我想随着函数老化(),struct类型数据输入。

我想将数据输入作为结构的数组,并将结构参数作为指针类型,但只能失败(年龄没有增加)

有什么问题?

#include <iostream>
using namespace std;
struct Person
{
    int age;
    double weight, height;
};
void aging(Person* p);
int main()
{
    Person ps[2];
    for (int i=0; i<2; i++){
        cout <<"age :";
        cin >> ps[i].age;
        cout <<"weight :";
        cin >> ps[i].weight;
        cout <<"height :";
        cin >> ps[i].height;
    }
aging(&ps[2]);
for (int i=0; i<2; i++){
    cout <<"age after1: "<<ps[i].age<<"weight after1: "<<ps[i].weight<<"height after1:"<<ps[i].height<<"n";
    }
return 0;
}
void aging(Person* p){
    p-> age++;
}

它看起来像您在数组ps的隔离元素上称为 aging。您将ps声明为两个元素,但尝试使用ps[2]访问第三个元素(请记住,C 数组以索引0开始)。如果您想在数组的最后一个元素上调用它,我认为您打算写aging(&ps[1])