×

C- POINTERS


In this chapter, we will learn about pointers.

Pointers in c is a variable that holds the address of another variable or a memory location. Pointers are used to allocate memory dynamically at run time.

Syntax - declaring pointer

//general syntax of declaring a pointer
data_type *variable_name;

Understanding pointers

To understand pointer variables, we need to understand two operators.

  • & operator -

    Used to get the memory address of a variable. This is also called the "Address of" operator.

  • * operator -

    Used to declare a pointer variable and to access the value of a memory address. It is also called as Value at address operator

C program to implement pointers

Lets see how to we can use pointer variable with value at address operator and Address of operator

File name - pointer_example.c
#include<stdio.h>
void main()
{
 // normal integer variable
 int normal_variable = 27;

 /*
 integer type pointer which can hold the address of integer data type
 This variable holds the address of normal_variable
 */
 int *pointer = &normal_variable;

 /*
 This will print the address of the *pointer variable
 Every time you execute this code, it may print different value because on every run the variable can use different memory location.
 */
 printf("Pointer variable is stored at address = %p\n", pointer); // %p becuase pointer variable

 /*
 Now lets change the value stored at pointer variable
 */
 //before changing lets print original value of pointer variable
 printf("Value of *pointer = %d\n", *pointer); // %d because integer variable

 *pointer = 30; // previous value 27 is replaced with new value 30

 // Now lets print the value of *pointer
 printf("After changing *pointer, new value of *pointer is %d\n", *pointer);

}
Output
Pointer variable is stored at address = 0x7ffcc0a3fbac
Value of *pointer = 27
After changing *pointer, new value of *pointer is 30

Description - Some points worth considering with pointers for above program

  • & operator

    This is used to represent address of a variable, in this program the variable is normal_variable which is stored at memory location 0x7ffcc0a3fbac

  • * operator

    This is used to represent value of a pointer variable, in this program the pointer variable is *pointer

  • pointer and *pointer

    pointer variable in the above program represents memory address of normal variable, where as *pointer variable holds the value. *pointer is same as using &normal_variable and *pointer is same as using normal_variable .

In the next chapter we will learn how to use STRUCTURE data type