我正在努力利用主题
char test;
char* testPtr = &test;
char** testPPtr;
testPptr = new char* [100];
for (int i = 0; i < 5; i++) {
cin >> testPtr;
testPPtr[i] = testPtr; // math, eng, history, kor, science
}
for (int j = 0; j < 5; j++) {
cout << testPPtr[j] << endl;
}
我认为
testPPtr[0]被分配给数学
testPPtr[1]被分配给eng
testPPtr[2]被分配给历史
但是,所有双指针都被分配了最后存储的值(science(。
为什么会发生这种情况?
我试过这个代码,但失败了。
char test;
char* testPtr = &test;
char** testPPtr;
testPptr = new char* [100];
for (int i = 0; i < 5; i++) {
cin >> testPtr;
testPPtr[i] = new char[100];
testPPtr[i] = testPtr;
}
for (int j = 0; j < 5; j++) {
cout << testPPtr[j] << endl;
}
如果有任何帮助,我将不胜感激:(
cin >> testPtr;
具有未定义的行为。它尝试在test
之后写入字符。
即使您修复了这个问题,例如通过声明std::string test;
,程序中也只有一个字符串,因此所有指针都指向同一个位置。
std::vector<std::string> subjects(5); // Creates 5 empty strings
for (std::string & subject : subjects)
{
std::cin >> subject; // Read each subject in
}
for (const std::string & subject : subjects)
{
std::cout << subject; // Write each subject out
}