初始化一个 const char* 数组

茶壶

我在 C++17 项目中工作,但必须使用 C-legacy-library。为此,我必须以 C 样式创建一个 const char* 数组,但我正在努力进行初始化。特别是,

#include <iostream>

int main(int argc, char* argv[])
{
    const int bound = 3;

    const char* inames[bound]{ "" };
    for(unsigned int i = 0; i < bound; i++) {
        const char *number = std::to_string(i).c_str();
        inames[i] = number;
    }

    for(unsigned int i = 0; i < bound; i++) {
        std::cout << "inames["
                  << std::to_string(i)
                  << "] = "
                  << inames[i]
                  << std::endl;
    }

    return 0;
}

返回

inames[0] = 2
inames[1] = 2
inames[2] = 2

作为输出,我不理解。我希望输出是

inames[0] = 0
inames[1] = 1
inames[2] = 2

谁能帮我指出我的错误?

约翰尼·约翰逊

问题是您没有任何地方可以实际存储字符串本身,只有指向它们的指针。

通过这样做,字符串存储在 std::strings 中,同时被普通 C 数组引用:

const int bound = 3;
std::vector<std::string> strings(bound);
const char* inames[bound];
for (unsigned int i = 0; i < bound; i++) {
    strings[i] =  std::to_string(i);
    inames[i] = strings[i].c_str();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章