如何将二维数组传递给函数? [英] How to pass 2d array to a function?

查看:133
本文介绍了如何将二维数组传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码按照预期的方式工作-会打印数组中的所有整数,但会产生警告。我想知道如何正确执行操作并避免警告。

This code works as it's supposed to do - it prints all ints in the array, but it produces a warning. I would like to know how to do it right and avoid the warning.

#include <stdio.h>
#include <stddef.h>

void print_all(int * array, ptrdiff_t num_rows, ptrdiff_t num_cols) {
    for (ptrdiff_t i = 0; i < num_rows; ++i) {
        for (ptrdiff_t j = 0; j < num_cols; ++j) {
            printf("%d\n", array[num_cols * i + j]);
        }
    }
}


int main() {
    int array[2][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8}
    };
    print_all(array, 2, 4);
}

这是警告:

$ clang -Wall -Wextra -pedantic -fsanitize=address -std=c11 arrays.c
arrays.c:18:15: warning: incompatible pointer types passing 'int [2][4]' to
      parameter of type 'int *' [-Wincompatible-pointer-types]
    print_all(array, 2, 4);
              ^~~~~
arrays.c:4:22: note: passing argument to parameter 'array' here
void print_all(int * array, ptrdiff_t num_rows, ptrdiff_t num_cols) {
                     ^
1 warning generated.

具有 print_all 函数仅接受具有以下内容的数组

Having print_all function only accept arrays with some specified number of columns is not acceptable.

推荐答案

如果编译器支持可变长度数组(VLA),然后您就可以这样做

If your compiler supports variable length arrays (VLA), then you can do this

void print_all(ptrdiff_t num_rows, ptrdiff_t num_cols, int array[num_rows][num_cols]) {
    for (ptrdiff_t i = 0; i < num_rows; ++i) {
        for (ptrdiff_t j = 0; j < num_cols; ++j) {
            printf("%d\n", array[i][j]);
        }
    }
}


int main(void) {
    int array[2][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8}
    };
    print_all(2, 4, array);
}

num_rows num_cols 参数必须在 array 参数之前,以便编译器知道数组的尺寸。 VLA允许您使用2D数组索引 array [i] [j] 来自己做数学。

The num_rows and num_cols parameters must be before the array parameter so that the compiler knows the dimensions of the array. The VLA allows you to use 2D array indexing array[i][j] instead of doing the math yourself.

如果您不能使用VLA或不想使用VLA,那么解决方案就是简单地传递2D数组的第一个元素的地址

If you can't use VLAs or don't want to use VLAs, then the solution is simply to pass the address of the first element of the 2D array

print_all(&array[0][0], 2, 4);

这篇关于如何将二维数组传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆