-3

Basically what I have is a function which accepts a 2 dimensional array as an argument, I'd like to then be able to create a 2 dimensional pointer to that array. Here's example code:

int main(){
    int a[3][3]={0,1,2,3,4,5,6,7,8};
    func(a);
}
int func(a[3][3]){
    int (*ptr)[3][3]=&a;//this is the problem
}

For some reason this works fine if the array is declared in the function (as opposed to being an argument) but I can't for the life of me figure out how to get around this.

2 Answers2

0

In C you pass an array to a function not directly but by reference instead - i.e. by passing a pointer to the first element of the array and - this is important - the array size.

Edit: when you declare X[5] the pointer you wanna use to call by reference is X i.e. calling the function with fun(X,5); where fun is defined with fun(int* ptr, int length)

Posted from mobile app, please edit for code display as appropriate.

Djordje
  • 186
  • 7
0

Arrays cannot be passed by value in C. The syntax in func does not mean what it looks like at first glance.

a in the function is actually a pointer, not an array, so you can achieve what you want by writing:

int (*ptr)[3][3]= (int (*)[3][3])a;

Working program, although it's probably simpler to pass &a to func and make func accept int (*)[3][3] directly:

#include <stdio.h>

int func(int a[3][3]){
    int (*ptr)[3][3]=(int (*)[3][3])a;

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

int main(){
    int a[3][3]={0,1,2,3,4,5,6,7,8};
    func(a);
}
Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365