C ++ Linked List指向另一个struct的指针内部的指针

时间:2014-06-28 13:13:55

标签: c++

如何使用从person读取的字符串初始化对象std::cin

班级ListElement代表一个链接列表。

#include <iostream>

using namespace std;

struct Stuff {
      char* name;
      char* surname;
      Date birthday; // Also a struct Date
};

struct ListElement {
      struct Stuff* person;          // Pointer to struct Stuff 
      struct ListElement* next;      // Pointer to the next Element
};

int main() {
      char input_name[50];
      cin >> input_name >> endl;

      ListElement* const start = new ListElement();
      ListElement* actual = start;

      start->next = NULL;
      *actual->person->name = input_name;  // not working :(
}

2 个答案:

答案 0 :(得分:0)

对于这些结构定义,main应该采用以下方式

#include <cstring>

//...

int main() {
      char input_name[50];
      cin >> input_name >> endl;

      ListElement* const start = new ListElement();
      ListElement* actual = start;

      actual->person = new Stuff();
      actual->person->name = new char[std::strlen( input_name ) + 1];
      std::strcpy( actual->person->name, input_name );
      // other code including deleting of all allocated memory
}

答案 1 :(得分:-1)

尝试类似的东西:

#include <iostream>
#include <list>
#include <string>

using namespace std;

struct Stuff
{
    string name;
};

int main() {
    list<Stuff> res;

    string in;
    cin>>in;

    res.push_back(Stuff{.name=in});

    for(Stuff& p : res)
        cout<<p.name<<endl;
    return 0;
}

汇编:

g++ test.cpp -std=c++0 -o test

没有c ++容器:

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


using namespace std;

struct Stuff {
    char* name;
    char* surname;
    Date birthday; // Also a struct Date
};

struct ListElement {
    struct Stuff* person;          // Pointer to struct Stuff 
    struct ListElement* next;      // Pointer to the next Element
};

int main() {

    ListElement l;

    string in;
    cin>>in;

    char* name = new char[in.size()+1];//+1 for \0
    ::strcpy(name,in.c_str());

    Stuff* tmp = new Stuff{
        .name=name,
        .surname = nullptr,
        //.birthday = date
        };

    l.person = tmp;
    l.next = nullptr;

    //do not forget to free Stuff.name
    return 0;
}