I want to learn c++, and here is my beginner question.
#include <iostream>
#include <string>
using std::cout;
using std::endl;
struct student{
struct address{
int no;
std::string city; //problem is here
};
char grade;
int num;
address *addr;
};
int main(){
student st1;
student *pSt1 = &st1;
pSt1->grade = 'A';
pSt1->num = 1234;
pSt1->addr->no = 123;
pSt1->addr->city = "Imladris";
return 0;
}
It crashes, but if I change std::string city
like this:
struct student{
struct address{
std::string city; // here
int no;
};
char grade;
int num;
address *addr;
};
It doesn't crash and returns 0... No errors nor warnings in either case. Maybe, there is no need to use a pointer here but as I said, I am learning c++. This is a sample code about pointers/structures.
I know how to fix it but I'd like to understand why it breaks. I change the declaration order of string city and it doesn't crash. Why?