C documentation V1 Help

Program: Pointer Demonstration

Program

#include <stdio.h> int main() { // Creating a variable int originalValue = 42; // Creating a pointer and initializing it with the address of the variable int *pointerToValue = &originalValue; // Accessing the value through the pointer printf("Original Value: %d\n", *pointerToValue); // Creating a new variable int newValue = 99; // Assigning the address of the new variable to the pointer pointerToValue = &newValue; // Accessing the new value through the updated pointer printf("New Value: %d\n", *pointerToValue); return 0; }

Explanation

This program demonstrates the following:

  1. Creation and Initialization of a Pointer:

    • A variable originalValue is created, and a pointer pointerToValue is created and initialized with the address of originalValue.

  2. Accessing Value through the Pointer:

    • The value of originalValue is accessed through the pointer using the dereference operator (*).

  3. Creating and Assigning a New Variable:

    • A new variable newValue is created.

  4. Assigning Address of New Variable to the Pointer:

    • The address of the new variable newValue is assigned to the pointer, updating it to point to the new location.

  5. Accessing Value through the Updated Pointer:

    • The value of the new variable newValue is accessed through the updated pointer.

This program provides hands-on experience with creating, initializing, assigning, and accessing pointers. It's a great way to reinforce the fundamental concepts of working with pointers in C.

Feel free to run the program and experiment with different scenarios. If you have any questions or if there's anything specific you'd like to explore further, let me know!

Last modified: 25 February 2024