Salma KHaled Salma KHaled - 19 days ago 8
C Question

How to build a table (2D array) with variable column length in C?

Is it possible to build a table (2D array) with variable column length ?? and how can I make this if it is possible?

Here I have the code but the column length is fixed.

#include <stdio.h>


const int CITY = 2; // column number
const int WEEK = 2; // row number
int i,j;
int z=0;
int c[4]={1,2,3,4};
int main()
{
int temperature[CITY][WEEK]; // create temp 2d array of city and weak
for ( i = 0; i < CITY; ++i)
{
for( j = 0; j < WEEK; ++j) {
temperature[i][j]= c[z];
z++;
}
}

printf("\nDisplaying values: \n\n");
for ( i = 0; i < CITY; ++i) {
for(j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d = %d\n", i, j, temperature[i][j]);
}
}
return 0;
}

Answer

You can create an array of pointers which will point to arrays of different lengths.

int *p[row], i;

for(i = 0; i < row; i++) {
    p[i] = malloc(len * sizeof(int)); // len is length for row i
}

Then you can access the jth element of ith row by p[i][j].

// displaying ith row of length = len

for ( j = 0; j < len; ++j) {
    printf("%d\n" p[i][j]);
}