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

不打扰是莪最后的温柔 提交于 2019-12-12 21:25:08

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14453147/c-is-moving-char-pointer-forward-by-adding-integer-of-bytes-legal-recommende

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!