Scroll Progress Bar

Pointers

A pointer in C is a variable that stores the memory address of another variable. It allows indirect access to the value of the variable it points to. Pointers are used to manage memory, dynamically allocate memory, and efficiently handle data structures.

Usage and Syntax:

To declare a pointer in C, use the * symbol before the pointer variable name, followed by the data type that the pointer points to.

data_type *pointer_variable_name;
Sample Code with Explanation and Output:

#include <stdio.h>

int main() {
    int num = 10; // A regular integer variable
    int *ptr; // Declare a pointer to an integer

    ptr = # // Store the address of 'num' in the pointer

    // Print the value of 'num' using the pointer
    printf("Value of num: %d\n", *ptr);

    // Change the value of 'num' using the pointer
    *ptr = 25;

    // Print the updated value of 'num'
    printf("Updated value of num: %d\n", num);

    // Working with arrays using pointers
    int arr[5] = {1, 2, 3, 4, 5};
    int *arrPtr = arr; // Point to the first element of the array

    // Print array elements using pointer arithmetic
    printf("Array Elements: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", *(arrPtr + i));
    }
    printf("\n");

    return 0;
}
Output:

Value of num: 10
Updated value of num: 25
Array Elements: 1 2 3 4 5
Explanation:
  • In the sample code, declare a regular integer variable num and initialize it with the value 10.
  • Then declare a pointer to an integer, ptr, using the * symbol. The pointer ptr is uninitialized at this point.
  • Next, store the memory address of the variable num in the pointer ptr using the & operator (ptr = & num;). Now, ptr points to the memory location of num.
  • Print the value of num using the pointer ptr. The *ptr syntax is used to dereference the pointer and access the value it points to. The output is Value of num: 10.
  • Then, change the value of num using the pointer ptr by assigning *ptr = 25;. The value of num is now updated to 25.
  • Work with arrays using pointers, an integer array arr with 5 elements, and declare a pointer arrPtr and point it to the first element of the array (int *arrPtr = arr;). The pointer arrPtr now points to the memory location of the first element of the array.
  • Print the elements of the array using pointer arithmetic. By using the *(arrPtr + i) syntax, access each element of the array sequentially. The output is Array Elements: 1 2 3 4 5.
  • The use of pointers allows us to manipulate variables indirectly and efficiently handle arrays and complex data structures in C. However, it requires careful management of memory to avoid undefined behavior and memory leaks.

What is a pointer in C?


Variable

What does a pointer store in C?


Address

What is the symbol for the address-of operator in C?


&

What is used to access the value a pointer points to in C?


Dereference

What type of memory does malloc allocate in C?


Dynamic