0

I want to display the elements of a 2D array by passing a pointer to a function. I successfully did it for 1D array.

#include<stdio.h>

void displaymat(int *a);

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

  displaymat(a);

  return 0;
}

void displaymat(int *a)
{
  int i;

  for(i=0;i<3;i++)
    printf("%d\n",a[i]);/*works for single dimensional array*/
}

But when I use displaymat(t), it gives me an error saying incompatible pointer type. However displaymat(&t[0][0]) seems to work. Why this apparent difference in passing pointer between 1D and 2D arrays?

2
  • 1
    int t[3][3]={1,2,3,4,5,6,7,8,9}; is a 1-D array. The value of t[1][2] is dependent on whether data is stored in row-major or column-major order. Are you sure this is what you intended to do? Commented Dec 4, 2013 at 18:14
  • @Iceardor-My bad, with proper initialization of the 2D array, displaymat(t) seems to work. What exactly is int t[3][3]={1,2,3,4,5,6,7,8,9}; then and why displaymat(t) gives me an error? Commented Dec 4, 2013 at 18:25

1 Answer 1

2

t is of type int**, which is a pointer to an array of int pointers.

a is of type int*

&t[0][0] is of type int*.

You should be able to call displaymat(t[0]), displaymat(t[1]), and displaymat(t[2])

Sign up to request clarification or add additional context in comments.

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.