使用指针初始化结构成员会导致分段错误

时间:2019-11-19 18:07:54

标签: string struct malloc

我在项目中遇到分段错误,并最终隔离了问题。下面的代码是重现该问题的简化版本。我不知道为什么不允许下面的作业。

任何人都可以解释为什么无法使用指针将值分配给struct成员吗?

#include <stdio.h>
#include <string.h>
#include <string>
#include <iostream>
#include <stdlib.h>

using namespace std;

struct info{
    string str1;
    string str2;
    string str3;
    string str4;
    string str5;
};

int main(void)
{
    struct info * arguments = (struct info*)malloc(sizeof(struct info));
    arguments->str1 = string("assignment");
    arguments->str2 = string("test");

    cout << arguments->depth << endl;

}

0 个答案:

没有答案