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;
}
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]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.