Siddhartha rao Siddhartha rao - 6 months ago 57
C Question

Jagged arrays in C

I came across this code while looking for jagged arrays in C. I am finding it difficult to understand the need for typecasting the calloc function since calloc() and malloc() return pointers.

int rowNum,colNum,i,j;
int** table;

Why are we using a pointer to a pointer and what does the line below return?

table = (int**)calloc(rowNum+1,sizeof(int*));

printf("The size of %d row",i+1);
table[i] = (int*) calloc(colNum+1,sizeof(int));

What's happening in the above line? Is the pointer pointing to the base element of the ith row?

//reading the elements in the row
table[i][0] = colNum;

printf("The size of row [%d]= %d",i+1,table[i][0]);

What is table pointing to here?


Table is pointing to the first element of dynamic array of pointers. And then we make each of those pointers point to an array of integers inside the for loop.

How this is different from a 2 Dim array is because in a matrix all rows have the same number of columns.

Our requirement is to obtain a jagged array. Take an array A of 5 columns and another array B of 4 columns if you combine both together in different rows you get a jagged array.

Now since we must assign like

//allocate an array of rowNum pointers and save to table
table[i] = (int*) calloc(colNum+1,sizeof(int));
//Yes it is pointing to the first element of the i-th row

In other words each table[i] represents each row which has variable number of coulumns(here as given by user).

I guess these links can help you out