9 Pointers

C Programming · Unit 9 · 6 hrs

Pointers

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

Pointers in short

This chapter introduces the pointer, a variable that stores the address of another variable, and follows it through pointer arithmetic, arrays, strings, function arguments and return values, structures, and dynamic memory allocation.

Pointers: notes

Introduction

A pointer is a variable whose value is the address of another variable, rather than an ordinary data value. Memory can be pictured as a long sequence of consecutively numbered storage locations, and the address of a data item is simply the number of its first storage location; a pointer variable is one that stores such an address. Pointers matter because they make several things possible: accessing array elements efficiently, returning more than one value from a function, working with memory allocated at run time, and building linked data structures such as linked lists, trees and graphs.

The & and * Operator

The address-of operator, &, returns the address of the variable it is placed before, so &age means the address of age. The indirection, or dereference, operator *, placed before a pointer variable, accesses the value stored at the address that pointer holds.

int age = 25, *page;
float sal = 50000, *psal;

page = &age;
psal = &sal;

printf("Address of age = %p, value = %d\n", (void *)page, *page);
printf("Address of sal = %p, value = %f\n", (void *)psal, *psal);

Declaration of Pointer

A pointer is declared like any other variable, but its name is preceded by *, and its declared type is the type of the variable it is meant to point to:

int age;
int *ptr;     /* ptr is a pointer to int */
ptr = &age;   /* ptr now points to age */

A pointer occupies its own storage, just like any other variable, though what it stores is an address rather than an ordinary value; on most current 32 bit and 64 bit systems a pointer typically occupies 4 or 8 bytes respectively, regardless of the type it points to.

Chain of Pointers

A pointer variable can itself be pointed to by another pointer, an arrangement called a pointer to pointer, or double indirection, declared with two asterisks: int **pptr;.

int a = 5, *pa, **ppa;
pa = &a;
ppa = &pa;

printf("%d\n", *pa);    /* 5, one level of indirection */
printf("%d\n", **ppa);  /* 5, two levels of indirection */

What this unit covers

  • Introduction
  • The & and * operator
  • Declaration of pointer
  • Chain of Pointers
  • Pointer Arithmetic
  • Pointers and Arrays
  • Pointers and Character Strings
  • Array of Pointers
  • Pointers as Function Arguments
  • Function Returning pointers
  • Pointers and Structures
  • Dynamic Memory Allocation

Pointers and Arrays

2080 · 10 marks

Explain the relation to array and pointer.Differentiate between call by value and call by reference with a suitable program.[2+8]

Show solved answer

Relation Between Array and Pointer, and Call by Value vs Call by Reference


(a) Relation Between Array and Pointer

In C, there is a strong relationship between arrays and pointers. Any operation that can be achieved by array subscripting can also be done with pointers.

Key Points:

  • An array name is itself an address (a constant pointer to the first element of the array).
  • Pointers and arrays are almost synonymous in terms of how they are used to access memory.
  • The pointer version of array operations is generally faster but harder to understand for beginners.

Illustration:

int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;   // ptr points to the first element of arr
Array NotationPointer NotationMeaning
arr[0]*ptrFirst element
arr[1]*(ptr + 1)Second element
arr[i]*(ptr + i)i-th element
&arr[i]ptr + iAddress of i-th element

Important Difference:

  • A pointer is a variable (its value can be changed).
  • An array name is a constant pointer (it always points to the first element and cannot be reassigned).

(b) Difference Between Call by Value and Call by Reference

Definition:

Call by Value: In call by value, a copy of the actual argument is passed to the formal parameter. The called function works on this copy, so any changes made inside the function do not affect the original variable.

Call by Reference: In call by reference, the address (reference) of the actual argument is passed to the function. The called function works directly on the original data using pointers, so changes made inside the function do affect the original variable.


Comparison Table:

FeatureCall by ValueCall by Reference
What is passedCopy of the valueAddress of the variable
Effect on original dataNo change in original variableOriginal variable gets modified
MemorySeparate memory for formal parameterFormal parameter refers to same memory
Return valuesCan return only one valueCan effectively return multiple values
SafetySafer (original data protected)Less safe (original data can be changed)
SpeedSlightly slower (copy is made)Slightly faster (no copy made)
Mechanism usedNormal variablesPointers

Program Demonstrating Both:

#include<stdio.h>
#include<conio.h>

/* Function prototypes */
void callByValue(int x);
void callByReference(int *x);

void main()
{
    int a = 15;
    int b = 15;

    clrscr();

    /* Demonstrating Call by Value */
    printf("--- Call by Value ---\n");
    printf("Before calling function, a = %d\n", a);
    callByValue(a);
    printf("After calling function, a = %d\n\n", a);

    /* Demonstrating Call by Reference */
    printf("--- Call by Reference ---\n");
    printf("Before calling function, b = %d\n", b);
    callByReference(&b);
    printf("After calling function, b = %d\n", b);

    getch();
}

/* Call by Value: works on a copy */
void callByValue(int x)
{
    x = x + 5;
    printf("Inside callByValue function, x = %d\n", x);
}

/* Call by Reference: works on original via pointer */
void callByReference(int *x)
{
    *x = *x + 5;
    printf("Inside callByReference function, *x = %d\n", *x);
}

Output:

--- Call by Value ---
Before calling function, a = 15
Inside callByValue function, x = 20
After calling function, a = 15

--- Call by Reference ---
Before calling function, b = 15
Inside callByReference function, *x = 20
After calling function, b = 20

Explanation of Output:

  • In Call by Value: a remains 15 after the function call because only a copy (x) was modified inside the function. The original variable a is not affected.

  • In Call by Reference: b becomes 20 after the function call because the address of b was passed (&b). Inside the function, *x directly modifies the original variable b. The original variable b is affected.


Summary: Use call by value when you want to protect the original data. Use call by reference when you want the function to modify the original variable or when you need to return multiple values from a function.

Open this answer on its own page →

2074 · 5 marks

Define pointer. Discuss the relationship between pointer and one-dimensional array. [1.5+3.5]

--- A pointer is a variable that stores the memory address of another variable. Instead of holding a data value directly, a pointer holds the address where that data is stored in memory. Syntax: Example: Here, ptr is a pointer to an integer. The operator & gives the address of a variable, and the...

Open this answer on its own page →

Dynamic Memory Allocation

2080 · 5 marks

What is dynamic memory allocation? Explain with a suitable program. [5]

Show solved answer

Dynamic Memory Allocation

Definition

The process of allocating memory at the time of execution (runtime) is called dynamic memory allocation. Unlike static memory allocation where the size is fixed at compile time, dynamic memory allocation allows a program to request and release memory as needed during execution.

Problems with static allocation (e.g., int emp[100];):

  • If fewer values are stored, memory is wasted
  • If more values are needed, we cannot store them

Dynamic memory allocation solves both problems. Memory is accessed through pointers, and the functions are available in stdlib.h / alloc.h.


Key Functions

FunctionPurpose
malloc()Allocates a block of memory of specified size
calloc()Allocates memory and initializes to zero
realloc()Resizes previously allocated memory
free()Releases dynamically allocated memory

Syntax of malloc():

pointer_variable = (datatype *) malloc(specified_size);

Example Program

The following program dynamically allocates memory for n integers entered by the user, stores them, and displays them.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr;
    int n, i;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    /* Dynamically allocate memory for n integers */
    ptr = (int *) malloc(n * sizeof(int));

    /* Check if memory was allocated successfully */
    if (ptr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    /* Input values */
    printf("Enter %d integers:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &ptr[i]);
    }

    /* Display values */
    printf("You entered:\n");
    for (i = 0; i < n; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    /* Release the allocated memory */
    free(ptr);

    return 0;
}

Sample Output

Enter number of elements: 4
Enter 4 integers:
10 20 30 40
You entered:
10 20 30 40

Key Points

  • malloc(n * sizeof(int)) allocates exactly the memory needed at runtime
  • The pointer ptr is used to access the dynamically allocated memory block
  • free(ptr) releases the memory back to the system after use
  • If allocation fails, malloc() returns NULL, which should always be checked
Open this answer on its own page →

2078 · 5 marks

Explain dynamic memory allocation with example. [5]

The process of allocating memory at the time of execution (runtime) is called dynamic memory allocation. Unlike static memory allocation where the size is fixed at compile time, dynamic memory allocation allows a program to request and release memory as needed during execution. --- Consider a sta...

Open this answer on its own page →

2075 · 5 marks

What is dynamic memory allocation? Discuss the use of malloc() in dynamic memory allocation with example. [1+4]

--- (a) What is Dynamic Memory Allocation? Dynamic memory allocation is the process of allocating memory to a program at the time of execution (runtime) rather than at compile time. In static memory allocation, the size of memory (e.g., an array) is fixed at compile time and cannot be changed dur...

Open this answer on its own page →

Pointers as Function Arguments

2079 · 5 marks

List any one advantage and disadvantage of the pointer. How do you pass pointers as function arguments? [5]

Returning more than one value from a function: A pointer allows a called function to directly modify the original variable in the calling function. This means a single function call can effectively return multiple modified values, which is not possible with normal call by value. --- Risk of unint...

Open this answer on its own page →

Function Returning pointers

2077 · 1 marks

Define pointer. How do you return pointers from functions? Explain with example. [1]

A pointer is a variable that stores the memory address of another variable. Instead of holding a data value directly, it holds the location (address) where the data is stored in memory. Syntax: Example: int p; declares p as a pointer to an integer. --- A function can return a pointer by specifyin...

Open this answer on its own page →