Search code examples
carrayspointersjagged-arrays

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;
scanf("%d",&rowNum);

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

table = (int**)calloc(rowNum+1,sizeof(int*));
for(i=0;i<rowNum;i++)
{

printf("The size of %d row",i+1);
scanf("%d",&colNum);
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?

for(j=1;j<=colNum;j++)
    {
    //reading the elements in the row
    scanf("%d",&table[i][j]);.
    }
    table[i][0] = colNum;

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

What is table pointing to here?


Solution

  • 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

    table=calloc(rowNum+1,sizeof(int*));
    //allocate an array of rowNum pointers and save to table
    ...
    table[i] = 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 columns(here as given by user).

    I guess these links can help you out