-2

We have

int i;

which have 4 bytes lets have address from 1000 to 1004. if we declared a pointer

int* p;
p = &i;

now is the pointer holds only 1000 or from 1000 to 1004? The pointer holds the addresses then why we need to declare a datatype to a variable? when we declare a datatype to pointer, can a pointer can be typecasted? why can't we use void* p which can hold any datatype?

4
  • 6
    The pointer holds only the memory address 1000. The fact that the memory of a (32-bit) int extends to 1003 is implied by the declaration of the pointer as being of int* type. You can use a void*, but then you lose information about the underlying type and its size. Sometimes recasting pointers or overlapping them, can be used to perform all sorts of efficient tricks, but those tricks are out of vogue nowadays. – Steve Feb 8 '18 at 14:40
  • 1
    @Steve has explained it quite beautifully. – Farhan Qasim Feb 8 '18 at 14:42
  • 2
    @Steve -- make your comment into an answer so it can be accepted by the original poster. – BobDalgleish Feb 8 '18 at 14:59
  • 2
    it might be worth adding as an example that any kind of pointer arithmetic (e.g. array access) depends on knowing the size of the elements, which depends on the 'type' of the pointer – GoatInTheMachine Feb 8 '18 at 16:02
9

The pointer holds only the memory address 1000. The fact that the memory of a (32-bit) int extends to 1003 is implied by the declaration of the pointer as being of int* type. You can use a void*, but then you lose information about the underlying type and its size. Sometimes recasting pointers or overlapping them, can be used to perform all sorts of efficient tricks, but those tricks are out of vogue nowadays

Not the answer you're looking for? Browse other questions tagged or ask your own question.