简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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