问题描述:

I'm trying to use a basic char* and can manage to do it in main, but when try putting it in another function, and then calling that function in main, I'll sometimes get a bus error or segmentation fault, but I'm not sure why.

This code works the way I'd expect:

#include <iostream>

using namespace std;

int main(void){

cout << "enter name:" << endl;

char *name[10];

cin >> *name;

cout << "hello: " << *name << endl;

return 0;

}

The output is:

enter name:

alex

hello: alex

But when I do this:

#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;

}

It compiles fine and the output gets to asking for the name, but I receive a buss error: 10. The output is:

enter name:

alex

Bus error: 10

Another issue I have is when I seem to do a very similar task, but do the same thing explicitly in main and add another function, I instead get a Segmentation fault: 11. My code is:

#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;

}

My output for this is:

this is a test

enter name:

alex

enter name:

Segmentation fault: 11

It doesn't make any sense to me and I'm not sure why I'd be getting two different errors.

网友答案:

The line

char *name[10];

defines an an array of 10 char* objects that haven't been initialized. Perhaps, you meant to use:

char name[10]; // An array of 10 chars.
cin >> name;
网友答案:

Pointer to char is confusing for beginner. I would advise the following:

void sayhello(){
    cout << "enter name:" << endl;
    char name[10];
    cin >> name;
    cout << "hello: " << name << endl;        
}

As said by Yu Hao, you have to learn more about pointer first.

相关阅读:
Top