#include <stdio.h>
void array(int *ar,int row,int col);
int main(void)
    int a[][2] = {
void array(int *ar, int row, int col)
    for(int i=0;i<row;i++)
        for(int j=0;j<col;j++)

What is the error ? I'm trying to pass an 2D array via function, and using the base address want to print the elements of the array? error

  • Did you try 'array(a, 3, 2);' ? It seems that your function is expecting a pointer as argument.
    – wallek876
    Jan 20 '15 at 10:36

A function that takes a 2D-array as an argument may have the following prototype

void foo(int arr[][<cols>]);

where <cols> is the number of columns in the array to be passed. For example

void foo(int arr[][3]);

declares a function foo that takes a 2D int array arr that has 3 columns and any number of rows in it.

As the error message shows, your function expects an int * while you are trying to pass a value of type int (*)[3][2]. These are two different types. The former is a pointer to an int while the latter is a pointer to 2D-array of ints (i.e., the type of &foo).

The following piece of code passes a 2D-array to foo (declared above)

int bar[3][3];

Notice that I'm not passing &bar because that would be a pointer to my 2D-array not my 2D-array itself.

Accessing the elements of the array within foo would be as follows

arr[0][0]; // accesses the element in the zeroth row and the zeroth column

If you want your function to take a pointer to a 2D-array of ints, it may have the following prototype

void baz(int (*arr_ptr)[][<cols>]);

where <cols> is the number of columns that are in the array that is pointed to by arr_ptr. For example

void baz(int (*arr_ptr)[][3]);

declares a function baz that takes a pointer to a 2D int array arr_ptr as an argument.

The following code passes a pointer to a 2D int array to baz

int bar[3][3];

Accessing the elements of the array within baz would be as follows

(*arr_ptr)[0][0]; // accesses the element at the zeroth row and the zeroth column

Notice that I had to dereference arr_ptr first to get the array back, then I accessed the element at [0][0].

  • Is it possible to pass the base address of a 2d array to function and then by pointer arithmetic print rest of the elements of the array ? And when i pass an 2d array to a function in the above example, (array(a);) then is (a) a pointer or what ? Jan 20 '15 at 15:27
  • @PrateekPande yes, but I don't see any reason why you would need to do that. Within in baz (declared above), you could do something like **(*x) to access (*x)[0][0] or **(*x) + 1 to access (*x)[0][1] and so on. And you are doing the wrong thing in your function. Please read the answer carefully to know why this is wrong and what is correct and feel free to ask if something is not clear!
    – kzidane
    Jan 20 '15 at 16:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .