简体   繁体   English

关于嵌套结构C ++

[英]about Nested Structures C++

I want to learn c++, and here is my beginner question. 我想学习c ++,这是我的初学者问题。

#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: 它崩溃了,但是如果我这样改变std::string city

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. 它不会崩溃并返回0 ...两种情况下均无错误或警告。 Maybe, there is no need to use a pointer here but as I said, I am learning c++. 也许这里不需要使用指针,但是正如我所说,我正在学习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. 我更改了字符串city的声明顺序,并且不会崩溃。 Why? 为什么?

You just came across the term Undefined behavior . 您刚遇到术语未定义行为 The end result of your code is compiler and platform dependent. 代码的最终结果取决于编译器和平台。 Dereferencing a pointer which value is not specified is (as mentioned here ) considered to be one of these cases where you are not able to predict the outcome of an operation. 解引用该值没有被指定为(如前所述指针这里被认为是这些情况下,你是不是能够预测的操作的结果之一)。

Keep your nested structure but add this to your member variable declaration: 保留嵌套结构,但将其添加到成员变量声明中:

address *addr = new address();

Or a better way is to use it as user @tobi303 mentioned: Don't declare it as a pointer, just an instance of address instead: 或更好的方法是将其用作用户@ tobi303 :不要将其声明为指针,而只是将其声明为address的实例:

address addr;

But use it this way: 但是用这种方式:

pSt1->addr.no = 123; // set
pSt1->addr.city = "Imladris"; // set

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM