总线错误10或分段错误11

bus error 10 or segmentation fault 11 when trying to use pointers to char* depending on encapsulation

本文关键字:错误 分段 总线      更新时间:2023-10-16

我正在尝试使用一个基本的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;        
}

正如于浩所说,你必须先了解更多关于指针的知识。