Code snippet 1:
int main(){
float fl;
int *i=&fl;
}
The error was:
error: cannot convert ‘float*’ to ‘int*’ in initialization int *i=&fl;
Code snippet 2:
int main(){
int i;
float *fl=&i;
}
The error was:
error: cannot convert ‘int*’ to ‘float*’ in initialization float *fl=&i;
Question
The datatype only helps in allocating the required memory size to the specified datatype. When it comes to the address of the memory, irrespective of the datatype of the variable, both addresses will be in the same format.
For Example-
int a;
float b;
cout<<&a<<" "<<&b;
The output was_
0x61fe1c 0x61fe18
So by looking at the address, one can’t differentiate between datatypes. So when the pointer deals with the addresses, why can’t we assign an integer pointer to the float variable?
NOTE: Here I’m not talking about the size of the datatype or the number of bytes that each datatype takes or the data format that each instruction is stored. I’m only interested in the address of the variable.
>Solution :
The datatype only helps in allocating the required memory size to the specified datatype.
This is not true. The type of a pointer p also tells the compiler what type to use for the expression *p.
If p is an int *, then *p has type int, and, if the program uses an expression such as a *p + 3, the compiler will generate an integer add instruction (or equivalent code). If p is a float *, then *p has type float, and, if the program uses an expression such as *p + 3, the compiler will generate a floating-point add instruction (or equivalent code). These different instructions will cause the computer to treat the bits of *p differently.
When it comes to the address of the memory, irrespective of the datatype of the variable, both addresses will be in the same format.
This is often true in C implementations but is not always true. The C standard allows pointers of different types to have different representations, with certain exceptions. (Pointers to character types and to void must have the same representation as each other. Pointers to structure types must have the same representation as each other. Pointers to union types must have the same representation as each other.)