Skip to content

C_Pointers.c

ani9977 edited this page Sep 11, 2024 · 1 revision

Here’s the updated C code with added documentation and an explanation:

#include <stdio.h>

/**
 * @brief The main function demonstrates pointer usage in C.
 * 
 * This function initializes an integer variable, assigns its address to a pointer,
 * and then prints both the pointer's address and the value it points to.
 * 
 * @return int Returns 0 to indicate successful execution.
 */
int main() {
    int number = 10;       /**< The integer variable initialized to 10. */
    int *ptr = &number;    /**< Pointer variable that stores the address of 'number'. */

    // Print the address stored in the pointer
    printf("Pointer value: %p\n", ptr);

    // Print the value at the address pointed to by 'ptr'
    printf("Pointer dereferenced value: %d\n", *ptr);

    return 0;   /**< Return 0 to indicate successful execution. */
}

Explanation

  1. Variable Initialization:

    • int number = 10; declares an integer variable number and initializes it with the value 10.
    • int *ptr = &number; declares a pointer ptr and assigns it the address of the number variable.
  2. Pointer Usage:

    • printf("Pointer value: %p\n", ptr); prints the address stored in the pointer ptr. The %p format specifier is used for printing pointer values.
    • printf("Pointer dereferenced value: %d\n", *ptr); prints the value at the address pointed to by ptr. The * operator is used to dereference the pointer, which gives the value of number.
  3. Return Statement:

    • return 0; indicates successful execution of the program. The value 0 is returned to the operating system.

Clone this wiki locally