简体   繁体   English

C++ 指向 char 数组中特定位置的指针数组

[英]C++ pointer array to specific location in char array

I had a problem with a Project.我有一个项目的问题。 It is generating C++ code to edit a file but there is one thing I'am stuck with.它正在生成 C++ 代码来编辑文件,但我坚持了一件事。 The file is stored inside an char array and I want to have a pointer array to a specific position inside the char array but I only get a pointer to one character of the array.该文件存储在一个 char 数组中,我希望在 char 数组中有一个指向特定 position 的指针数组,但我只得到一个指向数组中一个字符的指针。 What I want is something like this but on a very large array:我想要的是这样的,但是在一个非常大的数组上:

    char array[] = "Hello, how are you?";
    char* ptr = &array[7];
    *ptr = "who";
    std::cout << array << std::endl;

//Hello, who are you?

This is a stupid example but I hope it describes what I'am trying to do.这是一个愚蠢的例子,但我希望它描述了我正在尝试做的事情。

Currently I can only do this:目前我只能这样做:

    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?

But this is not easy to handle.但这并不容易处理。 I'd like to have a pointer array so it is easy to edit the parts of the array.我想要一个指针数组,以便编辑数组的各个部分。

I'am very thankful for any suggestions!我非常感谢任何建议!

Your immediate problem can be solved like this:您的直接问题可以这样解决:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM