我正在制作的更大程序的一部分需要从命令行读入并存储在类中。因为路径可以是任意大小,并且需要多个函数,所以我将它存储在头文件中的char*
中。但是,由于某种原因,当我给它赋值时,程序会出现段错误。C++全局字符指针?
调试器(GDB)显示如下:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b4828a in std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char> >(std::basic_istream<char, std::char_traits<char> >&, char*)()
from /usr/lib/libstdc++.so.6
这是我写的证明问题的程序:
TEST.CPP:
#include "test.h"
#include <iostream>
#include <cstring>
Test::Test() {
filepath = NULL;
}
void Test::set_path(char* string) {
char temp[strlen(string) + 1];
strcpy(filepath, temp);
}
char * Test::get_path() {
return filepath;
}
int main(int argc, char *argv[]) {
std::cout << "Enter a file path: ";
char *temp;
std::cin >> temp;
Test *temp2 = new Test();
temp2->set_path(temp);
std::cout << "Path: " << temp2->get_path() << std::endl;
}
test.h:
#ifndef TEST_H
#define TEST_H
class Test {
private:
char *filepath;
public:
Test();
void set_path(char *);
char * get_path();
};
#endif // TEST_H
我不知道它为什么崩溃。我正在做这个方法有什么问题吗?此外,我不想仅仅转换到string
,我想了解更多关于这个问题的信息。
在此先感谢!
“而不是只是切换到'字符串',我想了解更多关于这个问题。”为什么,你对'串'过敏? – 2011-12-25 04:54:22
我最终使用'std :: string''。我只是想弄清楚为什么'char *'不起作用。 – 2011-12-26 02:52:07