[英]Can't the double pointer be used like a dictionary?
我正在嘗試使主題更貼切
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] 分配給歷史
但是,所有雙指針都分配了最后存儲的值(科學)。
為什么會這樣?
我試過這段代碼,但我失敗了。
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.