I just read that we need to give the type of pointers while declaring them in C (or C++) i.e.:
int *point ;
As far as I know, pointers store the address of variables, and address occupies same amount of memory whatever may be the type. So, why do we need to declare its type?
A pointer declaration names a pointer variable and specifies the type of the object to which the variable points. A variable declared as a pointer holds a memory address.
There are majorly four types of pointers, they are: Null Pointer. Void Pointer. Wild Pointer.
The * symbol indicates that the variable is a pointer. To declare a variable as a pointer, you must prefix it with *. In the example above, we have done a pointer declaration and named ptr1 with the data type integer.
The type of the this pointer for a member function of a class type X , is X* const . If the member function is declared with the const qualifier, the type of the this pointer for that member function for class X , is const X* const . A better technique would be to declare member mutable.
Type-safety. If you don't know what p
is supposed to point to, then there'd be nothing to prevent category errors like
*p = "Nonsense"; int i = *p;
Static type checking is a very powerful tool for preventing all kinds of errors like that.
C and C++ also support pointer arithmetic, which only works if the size of the target type is known.
address occupies same amount of memory whatever my be the type
That's true for today's popular platforms. But there have been platforms for which that wasn't the case. For example, a pointer to a multi-byte word could be smaller than a pointer to a single byte, since it doesn't need to represent the byte's offset within the word.
Because:
The last two points don't apply to void
pointers, which is why they cannot by dereferenced and no pointer arithmetic may be done on them. The standard specifies that a void
pointer must be big enough to hold any kind of pointer (except function pointers, which are a different story altogether) and that assignment to and from void
pointers may be made without casts (at least in C, in C++ casts are always needed).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With