返回结构指针

时间:2016-09-25 19:59:52

标签: c++

我对c ++很新,需要以下代码的帮助。

#include <iostream>
using namespace std;

struct  student {
    string name;
    int age;
    float marks;
};

struct student *initiateStudent(string , int , float);

int main ( ) {
    int totalStudents = 1;
    string name;
    int age;

    float marks;

    cin >> totalStudents;

    student *stud[totalStudents];

    for( int i = 0; i < totalStudents; i++ )  {
        cin >> name >> age >> marks;
        stud[i] = initiateStudent(name,age,marks);
    }
    cout << stud[0]->name;

    return 0;
}

struct student *initiateStudent(string name, int age, float marks)
{
    student *temp_student;

    temp_student->name  = name;
    temp_student->age   = age;
    temp_student->marks = marks;
    return temp_student;
}

我需要在函数 initiateStudent 中通过传递成员名称 age <返回指针数组 stud 的结构指针/ strong>,标记。 我知道问题在于,当我返回主文件时,temp_student被销毁了。 所以我的问题是如何通过传递结构的成员然后返回信息到指针数组stud来完成它。

非常感谢。

2 个答案:

答案 0 :(得分:2)

半答案解释坏习惯:

#include <string>
#include <iostream>
#include <vector>

//using namespace std; often injects subtle bugs. Use with caution
// read more here: 
// http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice


struct student
{
    std::string name; // explicit namespacing reduces possibility of unwanted collisions
    int age;
    float marks;
    //added constructor in place of initialization function.
    student(std::string name, int age, float marks):name(name), age(age), marks(marks)
    {
    }
};

int main()
{
    int totalStudents = 1;
    std::string name;
    int age;

    float marks;

    while (!(std::cin >> totalStudents)) // testing input for success
                                         // Needed extra brackets caught by M.M
                                         // teach me to not test even a throw-away example    
    {
        std::cout << "must... have... good... input..." << std::endl; 
        cin.clear(); // clear the error and get rid of any other garbage the user may have input.
        cin.ignore(numeric_limits<streamsize>::max(), '\n');

    }

    //student *stud[totalStudents]; illegal in C++
    std::vector<student *> stud(totalStudents); // using dynamic array instead

    for (int i = 0; i < totalStudents; )// i++ removed
    {
        if (std::cin >> name >> age >> marks) //testing input
        {
            stud[i] = new student(name, age, marks); // using constructor
            i++; // and put here. Only increment if input is valid.
        }
        else
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    }
    std::cout << stud[0]->name;

    for (student * stu: stud) // cleaning up allocated memory
    {
        delete stu; 
    }

    return 0;
}

C ++的一个优点是你很少需要自我管理内存。事实上,huge advantages in not doing it以上和之后都不需要自己清理。

#include <string>
#include <iostream>
#include <vector>


struct student
{
    std::string name;     
    int age;
    float marks;

    student(std::string name, int age, float marks):name(name), age(age), marks(marks)
    {
    }
};

int main()
{
    std::string name;
    int age;
    float marks;

    std::vector<student> stud; // look ma! No pointer!

    while (std::cin >> name >> age >> marks) //exits loop on bad input
    {
        stud.emplace_back(name, age, marks); // building directly in vector
                                             // vector will size itself as needed.
    }
    std::cout << stud[0].name;

    return 0;
}

还有一点需要注意:>>是以空格分隔的。这意味着当它找到空格(空格,制表符,行尾......)时会停止,因此“John Jacob Jingleheimer-Shmidt”的名称将被命名为“John”。 >>然后会尝试将“雅各布”解释为age,这样做不会那么顺利。

答案 1 :(得分:0)

简单的解决方案是让您的initiateStudent()在堆上创建temp_student(使用new):并返回它。请记住堆分配的内存不会自动释放,所以不要忘记以后自己释放它。

#include <iostream>
#include <string>
using namespace std;

struct  student {
    string name;
    int age;
    float marks;
};

struct student *initiateStudent(string , int , float);

int main ( ) {
    int totalStudents = 1;
    string name;
    int age;

    float marks;

    cout << "Total student: ";
    cin >> totalStudents;
    cin.sync(); // very very important to not affect the next input (name)

    student* stud = new student[totalStudents];

    for( int i = 0; i < totalStudents; i++ ) 
    {
        cout << "Name: ";
        getline(cin, name);
        cin.sync();
        cout << "age: ";
        cin >> age;
        cout << endl;
        cout << "Marks: ";
        cin >> marks;
        cout << endl;
        cin.sync();

        stud[i] = *initiateStudent(name, age, marks);
    }

    cout << "Student 1: " << stud[0].name << endl;

    delete[] stud;
    stud = NULL;

    return 0;
}

struct student *initiateStudent(string name, int age, float marks)
{
    student *temp_student = new student;

    temp_student->name  = name;
    temp_student->age   = age;
    temp_student->marks = marks;
    return temp_student;
}