Why do we have pointers other than void

前端 未结 10 922
攒了一身酷
攒了一身酷 2020-12-30 22:54

I know that we have different pointers like int, float, and char. A void pointer is the only pointer which can hold all o

相关标签:
10条回答
  • 2020-12-30 22:54

    Dead simple:

    void* p;
    *p; // compile error!
    

    Or to put it in words; a void pointer can not be dereferenced.

    Perhaps you should rename the question why do we have pointers, or rather don't and just search for that question on SO.

    0 讨论(0)
  • 2020-12-30 22:54

    When You use pointer to float or int (for example) compiler knows how many bytes it should take from memory (sizeof(int) for int* for example).

    With void You would have to tell each time to compiler how many bytes it have to take (by writing (int*)some_void_ptr for example.

    But this is great simplification.

    0 讨论(0)
  • 2020-12-30 22:57
    int o = 12;
    void *i = &o;
    

    How would you access the int that i points to if there were only void pointers and no int*. You might know that on your platform an int is 4 bytes so you could memcpy 4 bytes from the start of whatever the void* points to into a temporary int and then use that. But that's not very convenient.

    Or given a

    struct Pair {
       char *first;
       char *second;
    };
    

    how useful would a void pointer to struct Pair be ? You'd likely want to access its first member and that's a lot of work if you couldn't have a pointer to a struct Pair.

    0 讨论(0)
  • 2020-12-30 23:00

    Type safety. Defining the type of pointers helps the compiler find errors where you are trying to use data of the wrong type through a pointer. That's the reason C has types in the first place.

    0 讨论(0)
  • 2020-12-30 23:02

    Two Words: Type Safety

    There's a little tidbit on type safety (or lack thereof) in C on Wikipedia that might shed some light for you.

    0 讨论(0)
  • 2020-12-30 23:04

    Is there any other reason that pointers other than void are present in C language?

    They are an awesome way to handle memory chunks freely. : )

    0 讨论(0)
提交回复
热议问题