8 Pointers And Dynamic Memory

C Programming · Unit 8

Pointers and Dynamic Memory

Exam-focused notes for Pointers and Dynamic Memory (C Programming, BIT102): what the TU syllabus asks and how it has actually been tested, with 7 solved past questions from this unit.

Pointers and Dynamic Memory in short

A pointer is a variable that stores a memory address. Pointers give direct control over memory and are the base of arrays, strings, lists and dynamic memory.

Pointers and Dynamic Memory: notes

Pointer concept and declaration

Every variable lives at an address in memory. A pointer holds that address. It is declared with *.

int a = 10;
int *p;        /* p can hold the address of an int */
p = &a;        /* & gives the address of a */
printf("%d\n", *p);   /* * reads the value at the address: 10 */
*p = 20;               /* changes a to 20 */
  • & is the address-of operator.
  • * is the dereference operator. It gives the value at the address.

A pointer has a type, so int * and char * move in different step sizes. Always give a pointer a valid address before using it. An unset pointer is a wild pointer and causes errors.

Pointer arithmetic

Only some operations are allowed on pointers: add or subtract an integer, subtract two pointers, and compare them.

If p is an int *, then p + 1 points to the next integer. The address increases by sizeof(int), usually 4 bytes.

int a[3] = {10, 20, 30};
int *p = a;
printf("%d\n", *(p + 1));   /* 20 */
p++;                        /* now points to a[1] */
printf("%d\n", *p);         /* 20 */

You cannot add two pointers, multiply them or divide them.

Double pointers

A double pointer (pointer to pointer) stores the address of another pointer. It is declared with two stars.

int a = 5;
int *p = &a;
int **pp = &p;
printf("%d %d %d\n", a, *p, **pp);   /* 5 5 5 */
**pp = 9;                              /* a becomes 9 */

Double pointers are used for arrays of strings, 2D dynamic arrays, and functions that must change a pointer.

What this unit covers

  • Pointer concept and declaration
  • Pointer arithmetic
  • Double pointers
  • Null pointers
  • Similarity between arrays and pointers
  • Pointers as function arguments
  • Dynamic memory allocation
  • Sizeof in DMA
  • Finding smallest element using pointers

Similarity between arrays and pointers

2081 · 10 marks

What is pointer? How it differs from array?Write a program to add two 2D matrices.[4+6]

Show solved answer

Pointer vs Array and 2D Matrix Addition


What is a Pointer? (4 marks)

A pointer is a variable that stores the memory address of another variable rather than storing a data value directly.

Declaration syntax:

data_type *pointer_name;

Example:

int x = 10;
int *ptr;
ptr = &x;   // ptr holds the address of x
printf("%d", *ptr);  // prints 10 (dereferencing)
  • & operator gives the address of a variable
  • * operator dereferences a pointer (accesses value at that address)

How Pointer Differs from Array

FeaturePointerArray
DefinitionVariable that stores address of another variableCollection of elements of same data type stored in contiguous memory
MemoryStores only an address (typically 4 or 8 bytes)Allocates memory for all elements at once
AssignmentCan be reassigned to point to different variablesArray name is a constant pointer; cannot be reassigned
InitializationMust be explicitly assigned an address before useMemory is allocated at declaration
ArithmeticPointer arithmetic moves to next memory locationArray index directly accesses elements
sizeofReturns size of pointer variable itselfReturns total size of all elements
Dynamic memoryCan use malloc()/calloc() for dynamic allocationSize is fixed at compile time (static)

Example showing difference:

int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;

// arr = ptr;  // ERROR: array name is constant
ptr = ptr + 1;  // VALID: pointer can be moved

Program to Add Two 2D Matrices (6 marks)

#include <stdio.h>

int main() {
    int r, c, i, j;

    // Input dimensions
    printf("Enter number of rows: ");
    scanf("%d", &r);
    printf("Enter number of columns: ");
    scanf("%d", &c);

    int A[r][c], B[r][c], C[r][c];

    // Input matrix A
    printf("\nEnter elements of Matrix A (%dx%d):\n", r, c);
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            printf("A[%d][%d]: ", i, j);
            scanf("%d", &A[i][j]);
        }
    }

    // Input matrix B
    printf("\nEnter elements of Matrix B (%dx%d):\n", r, c);
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            printf("B[%d][%d]: ", i, j);
            scanf("%d", &B[i][j]);
        }
    }

    // Add matrices A and B, store result in C
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }

    // Display result matrix C
    printf("\nResultant Matrix C = A + B:\n");
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            printf("%d\t", C[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Sample Output

Enter number of rows: 2
Enter number of columns: 2

Enter elements of Matrix A (2x2):
A[0][0]: 1
A[0][1]: 2
A[1][0]: 3
A[1][1]: 4

Enter elements of Matrix B (2x2):
B[0][0]: 5
B[0][1]: 6
B[1][0]: 7
B[1][1]: 8

Resultant Matrix C = A + B:
6    8
10   12

Logic Explanation

For two matrices A and B of same dimension (r x c):

$$C[i][j] = A[i][j] + B[i][j]$$

where i ranges from 0 to r-1 and j ranges from 0 to c-1.

Note: Matrix addition is only possible when both matrices have the same number of rows and columns.

Open this answer on its own page →

2080 · 5 marks

What is pointer? Explain the similarity between array and pointer in brief. [5]

Show solved answer

Pointer and Its Similarity with Array

What is a Pointer?

A pointer is a variable that stores the memory address of another variable rather than storing a direct value. It "points to" the location in memory where data is stored.

Syntax:

data_type *pointer_name;

Example:

int a = 10;
int *p;
p = &a;   // p holds the address of variable a

Here, &a gives the address of a, and *p (dereferencing) gives the value stored at that address, i.e., 10.


Similarity Between Array and Pointer

In C, arrays and pointers are closely related. The key similarities are:

1. Array Name as a Pointer

The name of an array acts as a constant pointer to the first element of the array.

int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;   // p points to arr[0]

Here, arr and &arr[0] are equivalent.


2. Accessing Elements

Array elements can be accessed using pointer notation, and pointer elements can be accessed using array notation.

Array NotationPointer NotationMeaning
arr[0]*p or *(p+0)First element
arr[1]*(p+1)Second element
arr[i]*(p+i)i-th element
printf("%d", arr[2]);    // Output: 30
printf("%d", *(p+2));    // Output: 30  (same result)

3. Pointer Arithmetic

Both arrays and pointers support arithmetic operations like increment and decrement to traverse elements.

p++;   // moves to the next element (next memory address)

4. Address Relationship

For an array arr:

  • arr = &arr[0] (address of first element)
  • arr + 1 = &arr[1] (address of second element)
  • arr + i = &arr[i] (address of i-th element)

Key Difference (Note)

Although similar, an array name is a constant pointer -- its address cannot be changed, whereas a pointer variable can be reassigned to point to different locations.

p = p + 1;   // Valid
arr = arr + 1; // ERROR: array name is a constant pointer

In summary, arrays and pointers are interchangeable in many contexts in C, making pointer knowledge essential for efficient array manipulation.

Open this answer on its own page →

2079 · 5 marks

Why array and pointer is similar? Write a program to show the similarity between an array and pointer. [5]

In C, arrays and pointers are closely related because: 1. Array name is a pointer: The name of an array acts as a constant pointer to the first element (base address) of the array. 2. Same memory access: Both arrays and pointers can be used to access memory locations using either subscript notati...

Open this answer on its own page →

Dynamic memory allocation

2080 · 5 marks

What is DMA? Write a program to read N numbers and find largest and smallest number using DMA. [5]

Dynamic Memory Allocation (DMA) is the process of allocating memory to a program at runtime (during execution) rather than at compile time. It allows a program to request memory as needed and release it when no longer required. In C, DMA is performed using the following standard library functions...

Open this answer on its own page →

Finding smallest element using pointers

2078 · 5 marks

Write a program to find smallest element of an array using a pointer. [5]

--- --- Concept Description ------ ptr = arr Pointer assigned the base address of the array ptr Dereferences pointer to get the value at that address ptr++ Moves pointer to the next array element (next memory location) smallest Stores the minimum value found so far --- 1. Pointer ptr is initializ...

Open this answer on its own page →

Double pointers

2077 · 5 marks

What is pointer? Illustrate the use of a double pointer with suitable example. [5]

A pointer is a variable that stores the memory address of another variable rather than storing a direct value. Syntax: Example: - &x gives the address of variable x - p gives the value at the address stored in p (dereferencing) --- A double pointer is a pointer that stores the address of another ...

Open this answer on its own page →

Pointer concept and declaration

0 · 5 marks

Describe the concept of pointer and its arithmetic with suitable examples. [5]

A pointer is a variable that stores the memory address of another variable rather than storing a data value directly. Declaration Syntax: Example: - &x gives the address of variable x - ptr gives the value at the address stored in ptr (dereferencing) --- Operator Name Meaning --------------------...

Open this answer on its own page →