Skip to content

Declaration and Initialization of Pointer Variables

In C programming, you can declare and initialize pointer variables to store memory addresses. Here’s how you can declare and initialize pointer variables:

1. Declaration of Pointer Variables:

  • To declare a pointer variable, you use the asterisk (*) symbol followed by the variable name.
  • The type of the pointer must match the type of the variable it will point to.

int *ptr;      // Pointer to an integer

float *ptr_f;  // Pointer to a float

char *ptr_c;   // Pointer to a character

2. Initialization of Pointer Variables:

  • Pointer variables can be initialized to the memory address of another variable or to NULL.
  • Initializing a pointer variable to NULL indicates that it does not point to any valid memory address.

int x = 10;    // Variable ‘x’ of type integer

int *ptr = &x; // Pointer ‘ptr’ initialized with the address of ‘x’.

Example:

#include <stdio.h>

int main()

{

    int x = 10;         // Declare and initialize an integer variable ‘x’

    int *ptr = &x;      // Declare and initialize a pointer ‘ptr’ with the address of ‘x’

    printf(“Value of x: %d\n”, x);      // Output: 10

    printf(“Address of x: %p\n”, &x);   // Output: Address of ‘x’ in hexadecimal format

    printf(“Value at address pointed by ptr: %d\n”, *ptr);  // Output: Value stored at the memory address pointed by ‘ptr’

    printf(“Address stored in ptr: %p\n”, ptr);  // Output: Address stored in ‘ptr’ in hexadecimal format

    return 0;

}

In this example:

  • We declare an integer variable x and initialize it with the value 10.
  • We declare a pointer variable ptr and initialize it with the address of the variable x using the “address-of” operator (&).
  • We then print the value of x, the memory address of x, the value stored at the memory address pointed by ptr, and the memory address stored in ptr.

When you run this program, it will print the values and memory addresses as specified.