Question

How to Insert and then print data from jagged array in below code ?

int *jagged[5];

jagged[0] = malloc(sizeof(int) * 10);
Was it helpful?

Solution

You can insert by adding a second subscript for the nested array's index.

int i;
for (i = 0; i < 10; ++i)
    jagged[0][i] = some_value;

and print like

int i;
for (i = 0; i < 10; ++i)
    printf("%d\n", jagged[0][i]);

Keep in mind that you need to keep track of each nested array's length on your own. Depending on your needs, you might do something like

int jagged_lengths[] = {10, 5, 4, 0, 3};
int i, j;

// Write some data
for (i = 0; i < 5; ++i) {
    jagged[i] = malloc(sizeof(int) * jagged_lengths[i]);
    for (j = 0; j < jagged_lengths[i]; ++j)
        jagged[i][j] = some_value;
}

// Read back the data
for (i = 0; i < 5; ++i)
    for (j = 0; j < jagged_lengths[i]; ++j)
        printf("%d\n", jagged[i][j]);

OTHER TIPS

first of all, why not define your array as a multi dimentional array? unless you want the size of each member different, you don't need to use malloc for each member, simply do:

int jagged[5][10];

as for iterating, you can do something like:

int i,j;
for (i = 0; i < 5; i++)
    for (j = 0; j < 10; j++)
       jagged[i][j] = i*j; //or any value you want


for (i = 0; i < 5; i++)
    for (j = 0; j < 10; j++)
        printf ("%d,%d: %d\n", i, j, jagged[i][j]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top