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.
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);
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加