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.
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 answerHide 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 Notation | Pointer Notation | Meaning |
|---|---|---|
arr[0] | *ptr | First element |
arr[1] | *(ptr + 1) | Second element |
arr[i] | *(ptr + i) | i-th element |
&arr[i] | ptr + i | Address 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:
| Feature | Call by Value | Call by Reference |
|---|---|---|
| What is passed | Copy of the value | Address of the variable |
| Effect on original data | No change in original variable | Original variable gets modified |
| Memory | Separate memory for formal parameter | Formal parameter refers to same memory |
| Return values | Can return only one value | Can effectively return multiple values |
| Safety | Safer (original data protected) | Less safe (original data can be changed) |
| Speed | Slightly slower (copy is made) | Slightly faster (no copy made) |
| Mechanism used | Normal variables | Pointers |
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:
aremains15after the function call because only a copy (x) was modified inside the function. The original variableais not affected. -
In Call by Reference:
bbecomes20after the function call because the address ofbwas passed (&b). Inside the function,*xdirectly modifies the original variableb. The original variablebis 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.
2074 · 5 marks
Define pointer. Discuss the relationship between pointer and one-dimensional array. [1.5+3.5]
Dynamic Memory Allocation
2080 · 5 marks
What is dynamic memory allocation? Explain with a suitable program. [5]
Show solved answerHide 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
| Function | Purpose |
|---|---|
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
ptris used to access the dynamically allocated memory block free(ptr)releases the memory back to the system after use- If allocation fails,
malloc()returnsNULL, which should always be checked
2075 · 5 marks
What is dynamic memory allocation? Discuss the use of malloc() in dynamic memory allocation with example. [1+4]
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]
Function Returning pointers
2077 · 1 marks
Define pointer. How do you return pointers from functions? Explain with example. [1]
Make Unit 9 stick
Practice CSC115 with flashcards & quizzes