Search code examples
c++c++11pointer-arithmetic

Void Pointer Arithmetic in C++11


I really want to use some void casts to hold binary data but this is either g++ warning cascade or a lot of casting. Is there an easy and safe way to do void pointer arithmetics in C++ (preferably c++11 or higher)?

I am working only on posix systems with gnu compiler so that not a problem here.

Usecase:

  • I have void * ptr to data with size > 1GB.

  • I have other function to do things, lets call it stuff() its part of external library and gets (void *, size_t) as params.

  • stuff(ptr, n) is likely to mutate underlying memory. basically I need to pass slice of ptr*.

Code suppose to, is, and i guess, will not be portable.

I guess i will go just with -Wno-pointer-arithmetics if i wont be able to find some more elegant solution, but the one proposed in answers helped


Solution

  • Depends on what you have in mind when asking about arithemtics. Following code is perfectly fine, and compilable by GNU g++ -std=c++11 :

    #include <cstdlib>
    #include <cstdio>
    
    int main()
    {
        void * x = std::malloc(100);
        std::printf("%p\n", x);
        std::printf("%p\n", x+20);
        return 0;
     }
    

    (Edit2) Question is pretty confusing, but if gnu compiler is something to work on, void pointer arithmetics is perfectly ok. GNU basically defines void * as pointer with one byte increments, and by that all statements in above code are correct. I did not tested it with other compilers, and as far as this question is considered, I do not have to.

    For compilers other than GNU, using unsigned integer type perfectly safe and correct : first cast pointer to either one of 1byte integer type:

    • size_t
    • uintptr_t / intptr_t
    • or if you know memory size and model - precise fixed width integer }

    If ever memory addressing will be changed to any other weird size per cell - you would need to use type that after adding +1 to address will point to next physical storage cell.

    Also to clarify = bool is not 1bit type... its padded (aliased) char with some wrapper magic inside.