Why should you indicate the type of pointers?

Why do you need to set the type of pointers? Are they just placeholders for addresses and all of these addresses? Thus, aren't all pointers, no matter what type set, occupy the same amount of memory?

+6
source share
2 answers

You do not need to specify the type of pointers. You can use void*everywhere that would force you to insert an explicit type, applied each time you read something, from the address indicated by the pointer, or write something to this address, or simply increase / decrease or otherwise manipulate the value of the pointer .

But people have long decided that they are tired of this way of programming and prefer typed pointers that

  • do not require drops
  • it is not always necessary to know the size of the pointed type (which is a problem that becomes even more difficult when it is necessary to take into account the correct alignment of the memory).
  • prevents accidental access to the wrong data type or advancing a pointer to the wrong number of bytes.

And yes, indeed, all data pointers, regardless of their type, occupy the same amount of memory, which is usually 4 bytes on 32-bit systems and 8 bytes on 64-bit systems. The type of the data pointer has nothing to do with the amount of memory occupied by the pointer, and the fact that no type information is stored with the pointer; the type of pointer is only useful to people and to the compiler, not to the machine.

+11

. , (, ), . , char , 0x01 . int 4 ( ), 0x04 , . , ( , void *), , , .

- C-, , :

#include <stdlib.h>
typedef void* pointer;
int main(void) {
    pointer numbers = calloc(10, sizeof(int));
    int i;
    for (i = 0; i < 10; i++)
        *(int*)(numbers + i * sizeof(int)) = i;
        /* this could have been simply "numbers[i] = i;" */
    /* ... */
    return 0;
}

, :

  • (int) ; : 4- , , , , . , !
  • , , . , 2 ^ 8 char, , , ( ) , , , .
  • , , ints - , ? , , , int , ( ), ? , , , , , , , .
+1

All Articles