【问题标题】:Can't the double pointer be used like a dictionary?双指针不能像字典一样使用吗?
【发布时间】:2021-07-08 07:29:39
【问题描述】:

我正在尝试使主题更贴切

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​​p>

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

如果有任何帮助,我将不胜感激:)

【问题讨论】:

  • 你的代码至少有内存泄漏,更喜欢使用容器。要修复错误,您需要在第一个 for 循环中使用 strncpy 或 memcpy。

标签: c++ pointers double-pointer


【解决方案1】:

cin &gt;&gt; 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2013-10-12
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多