#include<iostream>
#include <cstring>
using namespace std;
typedef struct {char *str;}String;
int main(){
String name,add;
cout<<"Name: ";
cin>>name.str;
cout<<"\n\tadd: ";
cin>>add.str;
cout<<"\n\tName:"<<name.str;
cout<<"\n\t Add:"<<add.str;
return 0;
}
输入成功,然后程序崩溃 显示错误:停止工作
答案 0 :(得分:4)
不,不,不,只需使用std::string
!更易于使用,更易于理解!
#include<iostream>
#include <string>
using namespace std;
int main(){
string name,add;
cout<<"Name: ";
getline(cin, name); // A name probably has more than 1 word
cout<<"\n\tadd: ";
cin>>add;
cout<<"\n\tName:"<<name;
cout<<"\n\t Add:"<<add;
return 0;
}
至于您的问题与原始代码有关,那就是您没有为char*
分配任何内存,并且正在读取不属于您的内存。
答案 1 :(得分:2)
str
是结构的成员及pointer
类型的成员,在执行name.str;
时,它没有valid memory
这就是为什么它在运行时崩溃的原因
首先将str
的内存分配为
name.str = new char [SIZE]; /* SIZE is the no of bytes you want to allocate */
完成工作后,使用delete
释放内存以避免内存泄漏。
delete [] name.str;