指向另一个结构的内部指针的结构指针

C++ Linked List Pointer to struct inside pointer to another struct

本文关键字:指针 结构 内部 另一个      更新时间:2023-10-16

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

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 :(
}

对于这些结构定义,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
}

试试这样做:

#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 
    ::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;
}