Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Is moving char pointer forward by adding integer of bytes legal/recommended?

Tags:

c++

offset

byte

I am looking for some ways to advance pointers to the beginning of files in compressed archives.

I have a character pointer to the beginning of the file that has been read into memory. The archive directory contains the offsets of each file. Is it legal/recommended to say:

char* beginning; //Imagine this is assigned to the beginning of the file in memory
int file1OffsetBytes = 1000; // Imagine the first file is 1000 bytes into the file

char* file1 = beginning + file1OffsetBytes;

Is this a bad idea? What is another way to do this?

like image 339
Satchmo Brown Avatar asked Dec 12 '25 14:12

Satchmo Brown


2 Answers

that is quite Ok. You only have to take care about out of bounds jumps... and one more thing: here is an size_t or ssize_t type usually used for memory buffers offset.

like image 140
zaufi Avatar answered Dec 15 '25 03:12

zaufi


Adding to a pointer (or subtracting from it) is legal as long as the resulting pointer still points to an element in the array or to the non-existent element right after the last existing one. Needless to say, you can only dereference a pointer pointing to an existing element and the element has to have been initialized if you're reading it through the pointer.

like image 25
Alexey Frunze Avatar answered Dec 15 '25 02:12

Alexey Frunze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!