总线错误10或分段错误11
bus error 10 or segmentation fault 11 when trying to use pointers to char* depending on encapsulation
我正在尝试使用一个基本的char*,并且可以在main中完成它,但当尝试将它放在另一个函数中,然后在main中调用该函数时,我有时会遇到总线错误或分段错误,但我不确定原因。
这个代码的工作方式我所期望的:
#include <iostream>
using namespace std;
int main(void){
cout << "enter name:" << endl;
char *name[10];
cin >> *name;
cout << "hello: " << *name << endl;
return 0;
}
输出为:
enter name:
alex
hello: alex
但当我这样做时:
#include <iostream>
using namespace std;
void sayhello(){
cout << "enter name:" << endl;
char *name[10];
cin >> *name;
cout << "hello: " << *name << endl;
}
int main(void){
sayhello();
return 0;
}
它编译得很好,输出开始询问名称,但我收到了一个总线错误:10。输出为:
enter name:
alex
Bus error: 10
我遇到的另一个问题是,当我似乎在做一个非常相似的任务,但在main中明确地做了同样的事情并添加了另一个函数时,我反而会遇到Segmentation错误:11。我的代码是:
#include <iostream>
using namespace std;
void sayhello(){
cout << "enter name:" << endl;
char *newname[10];
cin >> *newname;
cout << "hello: " << *newname << endl;
}
void testprint(){
cout << "this is a test" << endl;
}
int main(void){
testprint();
cout << "enter name:" << endl;
char *name[10];
cin >> *name;
cout << "hello: " << *name << endl;
sayhello();
return 0;
}
我的输出是:
this is a test
enter name:
alex
enter name:
Segmentation fault: 11
这对我来说毫无意义,我也不知道为什么我会犯两个不同的错误。
行
char *name[10];
定义了一个尚未初始化的10
char*
对象的数组。也许,您打算使用:
char name[10]; // An array of 10 chars.
cin >> name;
指向char的指针对于初学者来说是令人困惑的。我建议如下:
void sayhello(){
cout << "enter name:" << endl;
char name[10];
cin >> name;
cout << "hello: " << name << endl;
}
正如于浩所说,你必须先了解更多关于指针的知识。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)