Is it possible in C to pass a 2d array without eather of the sizes known? Something like this maybe:

#include <stdio.h>

void somefunction(int *array);

int main(void) {
  int array[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

  somefunction(array);

  return 0;
}

void somefunction(int *array) {
  printf("%d\n", array[3][2]);
}

I've also tried changing int *array to int *array[] (since 1 argument can be variable length) and int **array (worth a try). Any idea's? Thanks.

Recommended Answers

All 4 Replies

2D array arguments need a size for all but the first dimension. If you don't know the size until run time, or the function has to take different sized 2D arrays, you can use a pointer to a pointer instead. Then the calling code can either allocate memory to a pointer to a pointer or convert the array somehow. Note that a 2D array type is not directly convertible to a pointer to a pointer, so you have to do some kind of conversion. Here is a way that does not use malloc:

#include <stdio.h>

void f(int **p, int m, int n)
{
    int x, y;

    for (x = 0; x < m; ++x)
    {
        for (y = 0; y < n; ++y)
        {
            printf("%-4d", p[x][y]);
        }

        puts("");
    }
}

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

    for (x = 0; x < 3; ++x) p[x] = array[x];

    f(p, 3, 3);

    return 0;
}

Another way is passing just a 1D pointer and calculating the size of each dimension manually. It's not portable, and I don't recommend the trick, but I haven't seen any systems yet that it doesn't work on:

#include <stdio.h>

void f(int *p, int m, int n)
{
    int x, y;

    for (x = 0; x < m; ++x)
    {
        for (y = 0; y < n; ++y)
        {
            printf("%-4d", p[x * m + y]);
        }

        puts("");
    }
}

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

    f(&array[0][0], 3, 3);

    return 0;
}

You can scale both methods to more than two dimensions.

Error : Argument (int *array) is not a two dimensinal array. It is int pointer has an address of 1st element of array in main function.

void somefunction(int *array) {
  printf("%d\n", array[3][2]);  
}

So, modify your code with:

void somefunction(int *array) {
  printf("%d\n", *(array+0)); /* will print 1*/ 
  printf("%d\n", *(array+3)); /* will print 4*/ 
}

Okey, so 2D arrays of any size can't be passed. But you can make an array of pointers to 1D array's, and pass that. You can also pass the address of the first element and use that to calculate where [x][ y] are located. Interesting. Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.