如何在C++中用uint8_t指针保存数组的指定区间(索引5至25)
Hey there! Let's sort this out for you. Your original line uint8_t *pointer = array[5] - [25] isn't valid C++ syntax, but I totally get what you're aiming for—you want a pointer that references the slice of your array from index 5 to 25. Here's how to make this work correctly:
1. Point to the start of your target range
To get a pointer to the element at index 5, you have two equivalent options in C++:
- Use
array + 5: This leverages pointer arithmetic—since arrays decay to pointers, adding 5 moves the pointer 5 elements forward from the start of the array. - Use
&array[5]: This directly takes the address of the element at index 5.
Either way gives you a uint8_t* pointing exactly to the first element of your desired range. Here's a quick example:
#include <cstdint> // Required for uint8_t type int main() { uint8_t my_array[100]; // Example array—make sure it's large enough (at least 26 elements!) uint8_t* range_start = my_array + 5; // Or &my_array[5], both work }
2. Track the length of your range
A pointer only tells you where the range begins—you need to explicitly keep track of how many elements are in your interval. From index 5 to 25 inclusive, that's 25 - 5 + 1 = 21 elements. Store this as a constant for clarity and safety:
const size_t range_length = 21; // Total elements in the 5→25 range
3. Critical: Stay within array bounds
Always ensure your original array has at least 26 elements (since index 25 is the 26th element). Accessing elements beyond the array's allocated size is undefined behavior—this can lead to crashes, corrupted data, or weird bugs that are hard to track down.
Bonus: Safer range handling with C++20's std::span
If you're working with C++20 or later, std::span is a fantastic tool for this scenario. It wraps a pointer and length into a single, safe object that acts like a view of your array slice. It helps prevent accidental out-of-bounds access and makes your code more readable:
#include <cstdint> #include <span> // Required for std::span int main() { uint8_t my_array[100]; std::span<uint8_t> my_range(my_array + 5, 21); // Now you can access elements safely: // my_range[0] == my_array[5] // my_range[20] == my_array[25] // my_range.size() will return 21, so you can loop safely over the range }
To wrap up: Your pointer should start at array + 5 (or &array[5]), and you need to remember the range has 21 elements. If you can use C++20, std::span is the cleanest and most robust approach here.
内容的提问来源于stack exchange,提问作者warriorfenix

