指向另一个结构的内部指针的结构指针
C++ Linked List Pointer to struct inside pointer to another struct
如何用从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;
}
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- 指针或结构的矢量
- MSVC将仅移动结构参数解释为指针
- 如何访问指针结构的成员变量?
- 如何将变量从变量传递到指针结构对象
- 如何在函数中检索指针结构
- C :变量的点地址至指针结构成员的地址
- C++指针结构不会被删除
- 初始化指针结构 - 内存中的外观
- C++指针结构和多线程
- c++中指针结构的运算符重载
- 为什么我不能转发声明指针结构?
- C# 如何定义新的指针结构
- 如何处理大型指针结构
- 我怎么能写一个函数的定义在模板类中声明返回指针结构对象
- 我如何编程指针结构或类变量在c++
- 具有指针结构的类所需的析构函数
- 为什么在非指针结构上进行类型转换会出现语法错误
- 语法:做binary_search (STL)排序向量的指针结构
- /a.检测到Glibc.out: munmap_chunk():无效指针- c++结构体的动态数组