Pointer always stores a integer value i.e address so why do we need to declare them with different data type.
Like
int a=3,*p=&a;
char c=r,*cha=&r;
why can't we do like
int *c;
char r=a;
c=&r;
Pointer always stores a integer value i.e address so why do we need to declare them with different data type.
Like
int a=3,*p=&a;
char c=r,*cha=&r;
why can't we do like
int *c;
char r=a;
c=&r;
Essentially it's because
Pointer arithmetic would not work if the pointer types were not explicit.
The pointer to member operator would not work for struct
pointer types.
The alignment requirements for types can differ. It might be possible to store a char
at a location where it's not possible to store an int
.
The sizes of pointers are not guaranteed to be the same by the C standard: i.e. sizeof(int*)
is not necessarily the same as sizeof(char*)
. This allows C to be used on exotic architectures.
To pass to the "user" of the pointer information about what kind of data the pointer points to. Basing on that it will/may depend how the pointed data will be interpreted and handled. Any time you can use a pointer to void, in this case that information is not available. Then, the user of that pointer should know from other sources what is pointed and how to work with it.
Batcheba has already 4 good reasons. Let me give some less important ones:
function pointer and data pointer are not even compatible according to the standard (Harvard architecture with separate code and data address spaces, memory models of segmented architectures, etc.).
the optimizer can exploit the fact that pointer on different types generally do not overlap and can elide a lot of memory loads that way (https://en.wikipedia.org/wiki/Pointer_aliasing)
int *c;
char r=a;
c=&a;
In your declaration a is just a character not a variable. A pointer when defined can only store the address of a specific type of variable. If you declare c as int *c, the pointer can only point on variables of type integer.
Of course you can assign an address value to any type pointers.
int d;
char* cp = (char*)&d; // OK
float* fp = (float*)&d; // OK
But when you get content from the address, you MUST know the type. Otherwise the compiler will not know how to interpret it.