我正在製作的更大程序的一部分需要從命令行讀入並存儲在類中。因爲路徑可以是任意大小,並且需要多個函數,所以我將它存儲在頭文件中的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