Declaring a Pointer with the Wrong Type

You should make sure the type used to declare a pointer matches the type of data object it points to:

main()

{

int *ptr;

.

.

.

float val = 3.333333;

ptr = val; /* Error! */

printf( "val = %f\n", *ptr );

}

The program declares ptr as a pointer to an int. Later on, forgetting what type we used when declaring ptr, we assign it the address of the floating-point variable val.

Summary: Declaring a pointer with the wrong type can cause unwanted type conversions.

Since C allows you to assign any address to a pointer, the assignment doesn't cause an error. But accessing val through ptr creates problems. Because ptr is declared as a pointer to an int, the compiler does a type conversion on the float it points to, converting the float value to an int. The output is garbage:

val = 11242989923343410000000000000000000000000000000000000

000000000000000000000000000000000000000000000000000.000000

The following program cures the error by declaring ptr as a pointer to a float data type:

main()

{

float *ptr;

float val = 3.333333;

ptr = &val;

printf( "%f\n", *ptr );

}

Now it gives the correct output:

val = 3.333333