I created a small program to experiment with linked lists. When I ran it however, I got a "Access violation writing location" at jerry->age = 45. I'm not sure what I'm doing wrong.
#include <string>
#include <iostream>
using namespace std;
struct Person {
string name;
int age;
char gender;
struct Person* contact;
};
int main() {
struct Person* jerry = (struct Person*) malloc(sizeof(struct Person));
jerry->name = "Jerry";
jerry->age = 45;
jerry->gender = 'M';
jerry->contact = (struct Person*)malloc(sizeof(struct Person));;
printf("Hi! My name is %s.\n I am %d years old.\n I am ");
printf((jerry->gender == 'M') ? " a man.\n" : " a woman.\n", jerry->gender);
printf("I happen to know ");
}
EDIT:
My new code is as follows:
#include <string>
#include <iostream>
using namespace std;
class Person {
public:
Person(const string& name, int age, char gender, const Person* contact) : _name(name), _age(age), _gender(gender), _contact(contact) {}
public:
string getName() {
return _name;
}
int getAge() {
return _age;
}
char getGender() {
return _gender;
}
private:
string _name;
int _age;
char _gender;
const Person* _contact;
/*Person* getPerson() {
return _contact;
}*/
};
int main() {
Person jerry("Jerry", 45, 'M', nullptr);
Person simon("simon", 58, 'M', nullptr);
printf("Hi! My name is %s.\n I am %d years old.\n I am", jerry.getName(), jerry.getAge());
printf((jerry.getGender() == 'M') ? " a man.\n" : " a woman.\n", jerry.getGender());
printf("I happen to know ");
}
How would I access the pointer contact in the Person class?