如何打印c++中char类型指针的所有值

how to print all the values of pointers of pointers of char in C++?

本文关键字:指针 类型 char 何打印 打印 c++      更新时间:2023-10-16

如果我有这些代码:

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

我想读回使用打印键内的所有元素,我怎么能做到这一点?

我刚开始学习c++,指针让我不太舒服。

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

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

我想类似的东西,除非char **键有另一个含义?我怎样才能把它们全部打印出来呢?

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

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

假设数组类型为char **。你可以使用

printf("%c", array[i][j])

这里"%c"作为一个格式字符串,告诉它从下一个参数中期望一个字符。

相关文章: