7.6Arrays of Pointers and Dynamic Memory Allocation
Covers IGNOU MCS-201 §7.8
An ordinary array’s size is fixed when the program is written. Often the size is known only when the program runs: the number of rows the user asks for, for example. C handles this by requesting memory at run time and keeping its address in a pointer. An array of pointers then lets you manage several such blocks.
Arrays of pointers
int *ptr[3]; declares an array of pointers: three elements, each an int *. It is different from a two-dimensional array:
int arr[3][5];
int *ptr[3];
What is created
15 int objects in one block
3 pointers and no int objects
Rows
Fixed length 5, stored together
Each pointer must be made to point to separately obtained memory
Row lengths
All equal
May differ
Element access
arr[i][j]
ptr[i][j], once each ptr[i] points to valid memory
Dynamic memory allocation
The functions are declared in <stdlib.h>:
Function
Purpose
malloc(n)
Allocates n bytes; the contents are indeterminate (garbage)
calloc(count, size)
Allocates count × size bytes, all set to zero
realloc(p, n)
Changes the size of a previously allocated block
free(p)
Releases a block obtained from the functions above
Rules for using malloc:
Ask for count * sizeof(type) bytes: p = malloc(n * sizeof(int));.
malloc returns a void *, which C converts automatically to the pointer type on the left; a cast such as (int *) is allowed but not required.
Check the result:malloc returns NULL if the memory cannot be provided.
Use the block like an array: p[0] to p[n - 1].
Call free(p) exactly once when finished. Memory that is never freed is a memory leak.
Key takeaways
type *a[n]; is an array of n pointers; each must point to valid memory before use.
malloc, calloc and realloc allocate memory at run time; free releases it.
Always multiply by sizeof(type), check for NULL, and free each block once.
Dynamically allocated blocks can be used with subscript or pointer notation.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a fragment that asks the user for a number n, allocates an array of n integers, fills it with the squares 0, 1, 4, …, prints the last one, and releases the memory.
Show worked answer
int n, i; int *sq; scanf("%d", &n); sq = malloc(n * sizeof(int)); if (sq == NULL) { printf("Out of memory\n"); return 1; } for (i = 0; i < n; i++) sq[i] = i * i; printf("%d\n", sq[n - 1]); free(sq);. malloc reserves n × sizeof(int) bytes and returns the address, which is checked before use; sq[i] then works exactly like an array element; for n = 5 the last square printed is 16; free returns the block to the system.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/pointers/arrays-of-pointers-and-dynamic-memory-allocation/ to read this page.