Aad*_*hah 3 c++ segmentation-fault
#include <iostream>
using namespace std;
int main() {
char * c;
cin >> c;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试从长度未知的用户处获取C字符串行.我知道,如果我宣布c的char c[80],而不是char * c那么它会不会导致段错误.
但是如果我不想将用户限制为80 - 1字符呢?我可以使用一个非常大的数字,但这只会浪费空间.
我也想知道为什么上面的程序会导致段错误.根据我的理解,cin提取operator(>>)知道NULL终止C字符串.究竟是什么导致了这个问题?
程序段错误,因为指针c未初始化.在将数据读入缓冲区之前,您需要为缓冲区分配内存:
char * c = new char[80];
cin >> c;
cout << c << endl;
delete[] c; // Now you need to delete the memory that you have allocated.
Run Code Online (Sandbox Code Playgroud)
要避免将输入限制为N字符,请使用字符串.它们根据您的需要动态调整大小:
string c;
cin >> c;
cout << c;
// You do not need to manage string's memory - it is done automatically
Run Code Online (Sandbox Code Playgroud)