Join Regular Classroom : Visit ClassroomTech

Typecasting of a pointer in C

Typecasting is used to change a variable to a different type for a particular operation. We need to specify the type of the data whose address a pointer will hold, though all pointers are similar as they hold the addresses. The amount of space required by a pointer to store the address depends on the machine whether it is 32 bit or 64 bit.

For storing an address of a integer type variable a pointer needs 8 byte memory in case of 64 bit machine and needs 4 byte memory for 32 bit machine. Suppose, we have a pointer named “ptr” it contains a random address but it does not specify that whether it is an address of a char or int or double or float. A pointer variable on a 64-bit architecture occupies 8 bytes, no matter what type of pointer it is.

C compiler needs to know the type of the variable more than its size, because long and float both need 4 bytes, but we have to specify the compiler which one we want because their operations are different. pointers may be typecasted to another type from one type.

Example

/* C program to understand how to typecast a pointer */
/* www.codewindow.in */

#include<stdio.h>

int main() {
	int x=10;
	char ch='A';
	void *gp;			// It is a generic pointer
	gp=&x; 				// Address of int variable x is stored in gp
	printf("%d", *(int*)gp);	// Explicit typecasting it convert gp to integer pointer
	gp=&ch;				// Address of char variable ch is stored in gp
	printf("\n%c", *(char*)gp);	// Explicit typecasting it convert gp to character pointer
	return 0;
}

Output

10
A

Explanation
In the above example the void pointer gp has been typecasted to an integer pointer by using *(int *)gp in first case. Let’s break it down line by line:
1. *(int *)gp
2. *(integer type pointer gp)
3. Value at integer pointer gp
4. Value at &x
5. 10

Similarly, *(char *)gp was used to typecast the pointer gp to character pointer next time. Let’s also break it down:
1. *(char *)gp
2. *(character type pointer gp)
3. Value at character pointer gp
4. Value at &ch (as ch was an character variable)
5. A


You Missed

Also Checkout