首页 > 解决方案 > 指向 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?

但这并不容易处理。我想要一个指针数组,以便编辑数组的各个部分。

我非常感谢任何建议!

标签: c++arrayspointers

解决方案


您的直接问题可以这样解决:

#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;

推荐阅读