9

Below program (a toy program to pass around arrays to a function) doesn't compile. Please explain me, why is the compiler unable to compile(either because of technical reason or because of standard reason?)

I will also look at some book explaining pointers/multi dimensional arrays(as I am shaky on these), but any off-the-shelf pointers here should be useful.

void print2(int ** array,int n, int m);

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

void print2(int ** array,int n,int m)
{
    int i,j;
    for(i=0;i<n;i++)
    {
       for(j=0;j<m;j++)
       printf("%d ",array[i][j]);

       printf("\n");
    }
}
1
  • 1
    What is the compiler error message? Commented Jun 12, 2011 at 11:26

3 Answers 3

12

This (as usual) is explained in the c faq. In a nutshell, an array decays to a pointer only once (after it decayed, the resulting pointer won't further decay).

An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer.

Easiest way to solve it:

int **array; /* and then malloc */
Sign up to request clarification or add additional context in comments.

1 Comment

5

In C99, as a simple rule for functions that receive "variable length arrays" declare the bounds first:

void print2(int n, int m, int array[n][m]);

and then your function should just work as you'd expect.

Edit: Generally you should have a look into the order in which the dimension are specified. (and me to :)

4 Comments

What if i don't want to pass the dimensions from the function?
@Dchris, could you please be more clear what you want to know? You don't want to give dimensions at all, or you want to pass in fixed dimensions?
I want to pass in fixed dimensions
0

In your code the double pointer is not suitable to access a 2D array because it does not know its hop size i.e. number of columns. A 2D array is a contiguous allotted memory.

The following typecast and 2D array pointer would solve the problem.

# define COLUMN_SIZE 4
void print2(int ** array,int n,int m)
{
    // Create a pointer to a 2D array
    int (*ptr)[COLUMN_SIZE];
    ptr = int(*)[COLUMN_SIZE]array;

    int i,j;
    for(i = 0; i < n; i++)
    {
       for(j = 0; j < m; j++)
       printf("%d ", ptr[i][j]);
       printf("\n");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.