• admin@embedclogic.com

C-Pointer

Pointer

A pointer is a secondary data type that is used to declare a variable which can hold the address of another variable. Such variables, which are declared through the Pointer data type, known as pointer variables.

Syntax

datatype* pointer_variable_name;

Example

Let us understand the address assignment through this diagram –

Remember: Pointer can hold the address of same data type variable as itself.

Memory Map for the pointer address assignment

I above diagram, we have seen the address assignment of an integer variable into the pointer variable of the same datatype.Let us see how it works in memory –

1-Reserve a memory location 1024 by the variable i_var and initialize with value 5.

2-Reserve a memory location 1044 by the pointer variable i_ptr.

3-Assign the address of i_var(1024) to the pointer i_ptr.now 1044 has the value 1024(address of i_var).

Indirection Operator (*) use

Indirection operator(*) is used for fetching the value from the address held by the pointer.

See how the value at the assigned address held by pointer can fetch through the use of Indirection operator.

In Simple terms, you can say that one * cuts one & symbol.

Points must remember for the pointer
— The pointer’s data type must be similar to the data type of the variable that the address is stored in the pointer variable.

Example:

Output:

— If the pointer’s data type dissimilar to the data type of the variable then variable must be typecasted into pointer variabel’s data type before address assignment to a pointer variable.

Output :

You can see in above example ch_var has unsigned char dataType while i_ptr has unsigned int.During the address assignment, ch_var data type has changed temporarily to unsigned int through typecasting.

* symbol has a different meaning as per its uses.keep in mind that –

unsigned int i_ptr ———–> Here * indicates i_ptr is pointer variable.

*i_ptr ———————> Here * indicates the value at the address held by pointer i_ptr.

— A single increment in a pointer variable increases its address by the size of its data type.

Remember:

  • charpointer jumps only 1 byte in single increment whatever the processor size is.
  • intpointer jumps only 4 byte in single increment if processor is 32 bit.
  • float pointer jumps only 4 byte in single increment if processor is 32 bit.
  • double pointer jumps only 8 byte in single increment if processor is 32 bit.
Void Pointer

void pointer can hold the address of any dataType Variable because its data type is void.It is also known as a generic pointer because it can hold the address of any type variable.

Syntax

void *vptr;                               /*vptr is a void pointer*/

Output:

Null Pointer

null pointer is one which is not pointing to anything, i.e. it is assigned a null value. It is a good practice to initialize a NULL value to the pointer if it is not initialized.

Subscribe and stay updated with our latest articles.