Lee William
Lee William

Reputation: 125

How many ways to print our array of integer array?

I can declare array of integer array like this:

int dataA[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

and print the array out respectively like this two ways:

#include <stdio.h>

int main() {

    int dataA[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    int i = 0;
    for (; i < 3; i++) {
        int j = 0;
        for (; j < 3; j++)
            printf("%i,", dataA[i][j]);
        printf(";");
    }

    puts("");

    int dataB[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    int *p = (int *) dataB;
    int m = 0;
    for (; m < 3; m++) {
        int n = 0;
        for (; n < 3; n++)
            printf("%i,", *p + ((m * 3) + n));
        printf(";");
    }

return 0;
}

How about if I declare this way(is this declaration right?), how to print out them in this way?

#include <stdio.h>

int main() {

    puts("");

    int *dataC[3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    /*
     * How to print out the array in this situation?
     */

    puts("");

    int x[] = { 1, 2, 3 };
    int y[] = { 4, 5, 6 };
    int z[] = { 7, 8, 9 };
    int *dataD[3] = { &x, &y, &z };
    /*
     * How to print out the array in this situation?
     */

    return 0;
}

Upvotes: 1

Views: 66

Answers (1)

user12205
user12205

Reputation: 2702

dataC cannot be initialised this way. The elements of dataC is of type int *, while you are initialising them with int [].

As commented by @WhozCraig, it will be a valid initialisation if you did:

int *dataC[3] = {(int []){1, 2, 3}, (int []){4, 5, 6}, (int []){7, 8, 9}};

And you can output the array using the same method you used for dataA.

dataD cannot be initialised this way either. The elements of dataD is of type int *. x, y and z can be converted to type int *, but your use of the & operator is incorrect - &x here is of type int **, not int *.

It will be a valid initialisation if you did:

int *dataD[3] = { x, y, z };

If this is the case, you can simply output this array using the same method you used for dataA.

Upvotes: 3

Related Questions