Pointer to 2D Array Argument (C)

Quintus Primus

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.

M.M

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]

編集
0

コメントを追加

0

関連記事

分類Dev

Passing a char array as an argument in C turns into a pointer

分類Dev

C++ copying array into pointer argument

分類Dev

Array pointer from C to D

分類Dev

Pass 2d array as argument to a function using numpy and swig

分類Dev

2d dynamic int array in c

分類Dev

c ++ print / build 2d array

分類Dev

c - incrementing array pointer

分類Dev

Initializing a pointer to an array in C

分類Dev

declaring pointer to 1-D Array inside 2-D Array in C++

分類Dev

Pass 2d array in function - return 2d array from a function in C

分類Dev

Pass 2d array to subroutine as 1d argument fortran

分類Dev

malloc a array in C with loop dynanic array(2D)

分類Dev

C Pointer array is not working with memcpy

分類Dev

C *char pointer to char array

分類Dev

2D Array of Object pointers in C++

分類Dev

C++ 2d "dynamic" array in a class?

分類Dev

How to print a 2d character array C++

分類Dev

C++ - passing static 2d array to functions

分類Dev

define a 2D constant array in a C macro

分類Dev

How can I fully reallocate a 2D array in C?

分類Dev

How to pass a 2d array from Python to C?

分類Dev

How to sort strings in an 2D array in C

分類Dev

Is it possible to slice a column from 2d array in C

分類Dev

C: Passing one dimension of a 2D array results in segfault

分類Dev

C++ Displaying char inside a 2D array

分類Dev

C#Print 2D array prints split

分類Dev

Creating & Printing 2D array in C++

分類Dev

How to delete this 2d dynamic array in c++

分類Dev

Dynamically creating a 2D array of pointers using malloc in C