Search code examples
cpointersmemorytypeslow-level

Is it possible to create pointers in C without a specific datatype


So I started a programming project, and I found out it would make everything easier if I could just make a pointer without declaring it as char*, int* and so on and just specify the size somewhere else. I searched around but couldn't find anything useful.

Right now my idea would be to make everything a char* and just unite them with bit shifting and or operations if it isn't a string. If this is too low level for C, what language lets me do this, I prefer not to use assembly because it isn't cross platform enough.

edit: So i forget to mention it should allocate memory at runtime, and to not waste too much memory i want to allocate memory depending on the size. For example i want to allocate 1 byte for char sized values and 2 bytes for int sized values and so on. The size is predefined in a file, but is not known until the file is read which should be read in runtime rather then compiling time.


Solution

  • There is a generic pointer type in C for exactly this reason: void *.

    You can convert any data pointer type implicitly to and from void *:

    char foo[] = "bar";
    void *ptr = foo;
    
    // ...
    
    char *str = ptr;
    

    But be aware that you still have to know the correct type. Accessing an object through a pointer of the wrong type would be undefined behavior.


    There are two things you can't do with void *:

    • You can't do pointer arithmetics on it (this includes indexing). void is an incomplete type, so it doesn't have a known size. Some compilers allow arithmetics on void * by assuming the size of a char, but this is an extension and not portable.

    • You can't dereference a void *. void is "nothing", so it wouldn't be meaningful.