C++. Given the following struct declaration: struct Student { char * name; float
ID: 3695545 • Letter: C
Question
C++. Given the following struct declaration:
struct Student
{
char * name;
float gpa;
};
Implement 2 functions:
1. Student * createStudent(const char name[ ], float gpa); - This function creates a Student object dynamically and set its name as the passed in “name” and gpa as the passed “gpa.” When allocating memory for name part of the Student object, make sure it uses just enough number of chars, e.g. the code should allocate 5 chars for “Emma” The function returns a pointer to the newly created Student object.
2. bool destroyStudent(Student * aStudent); - This function deletes the Student object pointed to by “aStudent” and set it nullptr. Remember to deallocate all dynamically allocated memory. It returns true if the operation is successful and false if “aStudent” contains nullptr.
Explanation / Answer
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct Student
{
char * name;
float gpa;
};
Student * createStudent(const char name[], float gpa)
{
struct Student * student = new Student;
student->name = (char*)malloc(strlen(name) + 1);
strcpy(student->name, name);
student->gpa = gpa;
return student;
}
bool destroyStudent(Student*& aStudent)
{
if (aStudent)
{
cout << "Student is null";
free(aStudent->name);
cout << " I freed student";
delete aStudent;
cout << " I deleted aStudent";
aStudent = nullptr;
cout << " I nullptr = aStudent";
return true;
}
cout << "passed by a Student and it looks null";
return false;
}
int main(int argc, char** argv)
{
Student * student1 = createStudent("Danny", 10.5);
cout << "Name is: " << student1->name << " and there GPA is: " << student1->gpa << endl;
destroyStudent(student1);
if (student1)
{
cout << "Pointer is not null." << endl;
student1 = nullptr;
}
if (!student1)
{
cout << "Your pointer is null." << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.