带指针的C ++ struct数组

时间:2017-10-02 02:43:04

标签: c++ arrays pointers struct

我希望使用函数aging()从结构类型数据输入中将年龄增加1。

我想将数据输入作为struct数组输入,并将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++;
}

1 个答案:

答案 0 :(得分:1)

看起来你在数组// type Fork a = Left a | Right a // Left a :: { fork :: (a -> b, _) -> b } const Left = x => ({ type: Left, fork: (f,_) => f (x) }) // Right a :: { fork :: (_, a -> b) -> b } const Right = x => ({ type: Right, fork: (_,f) => f (x) }) // doA :: number -> number const doA = x => x + 1 // doB :: number -> number const doB = x => x * x // main :: Fork a -> a const main = f => // fork applies the left function (doA) to a Left // fork applies the right function (doB) to a Right f.fork (doA, doB) console.log (main (Left (3))) // => 4, doA (3) === 3 + 1 console.log (main (Right (3))) // => 9, doB (3) === 3 * 3的一个越界元素上调用了aging。您声明ps有两个元素,但尝试使用ps访问第三个元素(请记住,c ++数组从索引0开始)。如果你想在数组的最后一个元素上调用它,我认为你打算写ps[2]