如何打印c++中char类型指针的所有值
how to print all the values of pointers of pointers of char in C++?
如果我有这些代码:
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"
作为一个格式字符串,告诉它从下一个参数中期望一个字符。
相关文章:
- C++中的双指针类型转换
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 将类指针类型转换为键时出错
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- C++在一个映射中存储不同的指针类型(并处理销毁)
- 指针类型类成员的动态强制转换的恒定性是什么?
- 我正在尝试将表的地址传递给要在另一个函数中使用的指针,但得到不兼容的指针类型
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- STL 函数和函数类型与函数指针类型
- 如何调用指针类型的方法(禁用多态性)?
- 为什么新表达式可以正确生成指针类型,即使它应该返回 void*?
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 是否允许调用方对我的 Builder 类使用任何指针类型(包括智能指针)?
- OPENCL 警告:不兼容的指针类型将'float __global[16]'传递给类型为 '__global float4 的参数 *
- 专门用于"direct"函数类型(与函数指针类型相对)
- 指向成员的指针类型和模板
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 在C++17中,为什么类模板和函数模板的指针类型推导明显不一致
- 为什么允许将整型、枚举和指向成员的指针类型reinterpret_cast到自身?