Home >Backend Development >C++ >How Can I Correctly Pass a Multidimensional Array to a Function in C ?

How Can I Correctly Pass a Multidimensional Array to a Function in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-01 13:41:10706browse

How Can I Correctly Pass a Multidimensional Array to a Function in C  ?

Passing Multidimensional Array to Function in C

In this code snippet, an attempt is made to pass a C-style multidimensional array to a function that expects an array of integer pointers:

#include<stdio.h>
void print(int *arr[], int s1, int s2) {
    ...
}

int main() {
    int a[4][4] = {{0}};
    print(a,4,4);
}

This code compiles in C but not in C . Here's why:

  • In C, a multidimensional array can decay into a pointer to its first element. This means that the above code is equivalent to:
print(&a[0],4,4);
  • In C , this decay is not allowed. The array type int4 is not implicitly convertible to the pointer type int**. This explains the error message:

    cannot convert `int (*)[4]' to `int**' for argument `1' to `void print(int**, int, int)'

Solution:

To pass a multidimensional array to a function in C , one must explicitly convert it to a pointer of the appropriate type. This can be achieved using the following technique:

#include<stdio.h>
void print(int **arr, int s1, int s2) {
    ...
}

int main() {
    int a[4][4] = {{0}};
    print((int **)a,4,4);
}

By explicitly converting the array to a pointer using the (int )** cast, the code now compiles and behaves as intended in both C and C .

The above is the detailed content of How Can I Correctly Pass a Multidimensional Array to a Function in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn