Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Pointers to any type?

Tags:

c

I hear that C isn't so type-safe and I think that I could use that as an advantage for my current project.

I'm designing an interpreter with the goal for the VM to be extremely fast, much faster than Ruby and Python, for example.

Now I know that premature optimization "is the root of all evil" but this is rather a conceptual problem.

  • I have to use some sort of struct to represent all values in my language (from number over string to list and map)

Would the following be possible?

struct Value {
 ValueType type;
 void* value;
}
  • I would store the actual values elsewhere, e.g: a separate array for strings and integers, value* would then point to some member in this table.

  • I would always know the type of the value via the type variable, so there wouldn't be any problems with type errors.

Now:

Is this even possible in terms of syntax and typing?

like image 816
dragme Avatar asked May 29 '10 17:05

dragme


People also ask

Can a pointer be any type in C?

void pointer in C / C++A void pointer can hold address of any type and can be typecasted to any type.

Can pointers point to any data type?

Every pointer is of some specific type. There's a special generic pointer type void* that can point to any object type, but you have to convert a void* to some specific pointer type before you can dereference it.

What type are C pointers?

There are majorly four types of pointers, they are: Null Pointer. Void Pointer. Wild Pointer.

What can pointers point to in C?

The Pointer in C, is a variable that stores address of another variable. A pointer can also be used to refer to another pointer function. A pointer can be incremented/decremented, i.e., to point to the next/ previous memory location. The purpose of pointer is to save memory space and achieve faster execution time.


2 Answers

Yes, you can use a void* to point to anything, and then cast it to the proper type when needed (that's how malloc and such can work).

void* is basically "pointer to an arbitrary block of memory".

like image 103
Amber Avatar answered Oct 13 '22 18:10

Amber


If you know the range of types you want to support, this could easily be done with a union to avoid casts all over the place:

struct Value
{
    ValueType type;
    union
    {
        int*        iptr;
        char*       sptr;
        float*      fptr;
        struct map* mptr;

        /* ... */

        void* vptr; /* catch all, extensions */

    } ptrs;
};
like image 44
Nikolai Fetissov Avatar answered Oct 13 '22 17:10

Nikolai Fetissov