Interview

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


<predata-previewers=””>// 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