0

Say I have 64000 bytes in memory at a certain address. I have a pointer char* pointing to the first byte. How would I convert that area of memory to an array of 64000 bytes?

I would prefer not to make a new copy of the memory area if possible.

  • 2
    As asked, I'd say you're already pretty well set by indexing the pointer you have. – Quentin Feb 10 '21 at 21:56
  • 1
    You don't need to. If you have a pointer to the first character in a contiguous block of memory, then indexing or array operations on that pointer treat that block of memory as if it is an array. For example, `ptr[200]` or, equivalently, `*(ptr + 200)`, will access the 201'th character (since indexing is zero-based) in the memory block. While `ptr` is not actually an array, if it points to the first character in a block of memory, it can be treated *as if* it is an array that exists in that block of memory for most operations that matter on arrays. – Peter Feb 10 '21 at 22:04
  • I didnt know what you meant (I am a noob), but a google search using the word "index" sent me here. https://stackoverflow.com/questions/4622461/difference-between-pointer-index-and-pointer , reading that i learned that I can simply add [] to the char pointer to get the array element i want. – soma wheels Feb 10 '21 at 22:10
  • @somawheels that is correct. You can use the operator `[]` directly on your pointer without any additional work. – Drew Dormann Feb 10 '21 at 22:12

1 Answers1

3

You could create a std::string_view to look at what's there:

#include <string_view>

auto memview = std::string_view(reinterpret_cast<const char*>(the_pointer), 64000);

for(auto ch : memview) {
    std::cout << static_cast<int>(ch) << '\n';
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Wouldn't `const_cast` or no cast t all be more appropriate? It's already a `char*` – doug Feb 10 '21 at 22:44
  • @doug It's not necessary to cast at all from `char*` to `const char*`. I did it this way so it wouldn't matter what the pointer is pointing at. It could be a `foo*`. – Ted Lyngmo Feb 10 '21 at 22:51