gpt4 book ai didi

c++ - 如何在 C++ 中打印 char 指针的所有指针值?

转载 作者:行者123 更新时间:2023-11-28 03:44:47 25 4
gpt4 key购买 nike

如果我有这些代码:

unsigned char **keys;
int *num_keys;

int num_images = (int) key_files.size(); // the result is 10 for example

keys = new unsigned char *[num_images];
num_keys = new int[num_images];

/* Read all keys */
for (int i = 0; i < num_images; i++) {
keys[i] = NULL;
num_keys[i] = ReadKeyFile(key_files[i].c_str(), keys+i);
}

我想使用 printf 读回键内的所有元素,我该怎么做?

我刚开始接触 C++,指针让我不太舒服。

对于其他语言,我认为它应该是一个二维数组:array[a][b] 然后我可以像这样循环它:

for(int i=0; i<a; i++)
for(int i=j; j<b; j++)
printf(array[i][j]);

我是这么想的,除非 char **keys 有其他含义?以及如何打印所有这些?

提前致谢。

最佳答案

在 C++ 中,你的程序可以这样写:

#include <vector>
#include <iostream>

//...

const unsigned int num_images = key_file.size();

std::vector<unsigned char *> keys(num_images);
std::vector<int> num_keys(num_images);

for (std::size_t i = 0; i != num_images; ++i)
{
num_keys[i] = ReadKeyFile(key_files[i].c_str(), &keys[i]);

// if the key is a null-terminated string:
std::cout << "The key[" << i << "] is: '" << keys[i] << "'." << std::endl;

// if the key is just a bunch of bytes, num_keys[i] in number:
for (int j = 0; j != num_keys[i]; ++j)
{
std::cout << "key[" << i << "][" << j << "] = " << (unsigned int)(keys[i][j]) << std::endl;
}
}

我把打印和读取放在同一个循环中;如果愿意,您也可以在单独的循环中进行打印。

关于c++ - 如何在 C++ 中打印 char 指针的所有指针值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7983631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com