Interview

Can you implement a jagged array in C/C++?

Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays.

Example:

arr[][] = { {1, 3, 8},
            {1, 2},
            {9, 0},
            {10, 11, 4, 20, 50},
            {30}
          };
// C program to show the 
// implementation of Jagged Arrays 

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

int main() 
{ 

	int row0[3] = { 1, 3, 8 }; 
	int row1[2] = { 1, 2 };
	int row2[2] = {9,0};
	int row3[5] = {10,11,4,20,50};
	int row4[1] = {30};

	int* jagged[5] = { row0, row1,row2, row3, row4 }; 

	// Array to hold the size of each row 
	int Size[5] = { 3, 2, 2, 5,1 }, k = 0; 

	// To display elements of Jagged array 
	for (int i = 0; i < 5; i++) { 

		// pointer to hold the address of the row 
		int* ptr = jagged[i]; 

		for (int j = 0; j < Size[k]; j++) { 
			printf("%d ", *ptr); 

			// move the pointer to the 
			// next element in the row 
			ptr++; 
		} 

		printf("\n"); 
		k++; 

		// move the pointer to the next row 
		jagged[i]++; 
	} 

	return 0; 
} 

Related Articles

Back to top button