C++ 为什么这个程序会崩溃? #包括 #包括 使用名称空间std; typedef结构{char*str;}字符串; int main(){ 字符串名称,添加; coutname.str; coutadd.str; 不,不,不,只是使用!更容易使用,更容易理解 #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; } #包括 #包括 使用名称空间std; int main(){ 字符串名称,添加; cout

C++ 为什么这个程序会崩溃? #包括 #包括 使用名称空间std; typedef结构{char*str;}字符串; int main(){ 字符串名称,添加; coutname.str; coutadd.str; 不,不,不,只是使用!更容易使用,更容易理解 #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; } #包括 #包括 使用名称空间std; int main(){ 字符串名称,添加; cout,c++,C++,str是结构的一个成员,它属于指针类型,在执行name.str;操作时,它没有任何有效内存,这就是它在运行时崩溃的原因 首先为stras分配内存 #include<iostream> #include <string> using namespace std; int main(){ string name,add; cout<<"Name: "; getline(cin, name); // A name probably ha

str
是结构的一个成员,它属于
指针类型,在执行
name.str;
操作时,它没有任何
有效内存
,这就是它在运行时崩溃的原因

首先为
str
as分配内存

#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;
}
工作完成后,使用
delete
释放内存,以避免内存泄漏

name.str = new char [SIZE]; /* SIZE is the no of bytes you want to allocate */

你应该学习指针,它们不仅仅是“神奇的”指向某个有效的位置,您必须使它们指向某个位置。当您将调试器连接到该位置,并逐行遍历它时,它失败在哪里?
str
指向某个半随机位置,
std::cout
尝试写入该位置时,您的操作系统会看到一个恶意程序试图写入内存,而该内存无法写入首先为str分配内存,然后…?你难道没有忘记需要调用
delete[]的警告吗
不泄漏内存?@PaulMcKenzie是的,一旦工作完成,内存肯定会被释放。我以前经常用turboc++编写代码,因为大学时代已经过时,而且turboc++没有类似字符串的东西。所以,谢谢你,或者让我们了解一下
delete [] name.str;