c++ - 指向 char 数组中特定位置的 C++ 指针数组
问题描述
我有一个项目的问题。它正在生成 C++ 代码来编辑文件,但我坚持了一件事。该文件存储在一个 char 数组中,我希望有一个指针数组指向 char 数组中的特定位置,但我只得到一个指向数组中一个字符的指针。我想要的是这样的,但是在一个非常大的数组上:
char array[] = "Hello, how are you?";
char* ptr = &array[7];
*ptr = "who";
std::cout << array << std::endl;
//Hello, who are you?
这是一个愚蠢的例子,但我希望它描述了我正在尝试做的事情。
目前我只能这样做:
char array[] = "Hello, how are you?";
char* ptr = &array[7];
*(ptr) = 'w';
*(ptr+1) = 'h';
*(ptr+2) = 'o';
std::cout << array << std::endl;
//Hello, who are you?
但这并不容易处理。我想要一个指针数组,以便编辑数组的各个部分。
我非常感谢任何建议!
解决方案
您的直接问题可以这样解决:
#include <cstring> // std::memcpy
char array[] = "Hello, how are you?";
char* ptr = &array[7];
std::memcpy(ptr, "who", 3); // copy 3 chars from the character literal "who" to ptr
std::cout << array << std::endl;
推荐阅读
- sql - 查找以文件夹名称结尾的所有行
- react-native - 如何在 react-navigation-drawer Drawer 组件中获取当前的 routeName?
- python - 如何更改 dask 数据框中列的数据类型?
- pytorch - 如何从 torchvision.datasets.ImageFolder 获取 n 个图像
- wordpress - 如何调整页脚选项卡上重叠的wordpress侧小部件?
- java - 在设备上使用 sqlite 数据库但模拟器工作正常时出现 NullPointerException
- python - 使用python弹出数据框单元格中的第一个元素
- python - ValueError:形状(20,14)和(13,1)未对齐:14(dim 1)!= 13(dim 0)
- python - 如何从 Selenium Python 中的按钮中抓取数据
- flask - 每 N 小时执行一次任务