返回指向动态数组中最年轻学生的指针

时间:2014-03-21 13:28:40

标签: c++ pointers struct

我目前正在尝试编写一些函数,它将遍历动态数组,该数组以这种格式保存学生记录:

名称ID年龄

一旦此函数找到最年轻的年龄,请将其作为指向main函数的指针返回并输出。

问题是函数属于Student类型,这是我的结构;格式如下:

struct Student{
string name;
string id;
int age;

};

我正在努力返回指针(ptr)并将其输出到控制台,因为它正在输出(我认为)是内存位置......

到目前为止,这是我的代码,

任何建议都会非常有用。

结构:

struct Student{
string name;
string id;
int age;

};

函数调用:

cout << "Youngest: " << youngest(student_Dynamic, sizeOf) << endl;

功能:

    Student* youngest(Student* s, int size)
{
    int tempAge = 0;
    int youngestAge = 100;
    Student *pt = new Student;

    for (int i = 0;i < size;i++)
    {
        tempAge = (s+i)->age;

        if (tempAge < youngestAge)
        {
            youngestAge = tempAge;
            pt->age = youngestAge;          
        }
    }   
    return pt;  //Here I am trying to return the pointer so that it outputs the youngest age
                //to the console window...

}

更新:

现在,'Billy Pilgrim'回答了这个问题

谢谢大家的建议!

1 个答案:

答案 0 :(得分:0)

您正在返回指针,即正在打印的指针。它应该是这样的:

Student * s = youngest(student_Dynamic, sizeOf);
cout << "Youngest: " << s->name << endl;

(不确定sizeOf是什么:)。