Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Jagged Array In c

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

int *jagged[5];

jagged[0] = malloc(sizeof(int) * 10);
like image 759
Muhammad Faisal Avatar asked May 26 '26 19:05

Muhammad Faisal


1 Answers

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]);
like image 108
Daniel Lubarov Avatar answered May 28 '26 14:05

Daniel Lubarov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!