在函数中操作多维数组 [英] Manipulate multidimensional array in a function

查看:37
本文介绍了在函数中操作多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里阅读了很多内容并尝试了很多,但我找不到将多维数组传递给 C 中的函数、更改某些值并以某种方式返回新数组的方法.找到一种方法将该数组进一步传递给另一个函数并执行相同的操作,这一点很重要.

I read a lot of stuff in here and tried many but i couldn't find a way to pass a multidimensional array to a function in C, change some of the values and somehow return the new array. It's important to find a way to pass that array further to another function and do the same thing.

我想找到一种方法将数组传递给一个函数.然后将它从第一个函数传递给第二个函数,在那里做一些事情(也许打印,也许更改值),然后再次将它用于第一个函数最后在 main 中使用该数组.

I would like to find a way to pass the array to a function.Then pass it from the first function to a second one,do something there(maybe print,maybe change values),then use it again to the first function and finally use that array in main.

我最后一次尝试是:

void func(int multarray[][columns]){
    multarray[0][0]=9;
}

int main(){
    int rows;
    int columns;
    int multarray[rows][columns];
    func(multarray);
    return 0;
}

我也试过这个:

void func(int multarray[rows][columns]){
    multarray[0][0]=9;
}

int main(){
    int rows;
    int columns;
    int multarray[rows][columns];
    func(multarray);
    return 0;
}

我也试过这个:

int
getid(int row, int x, int y) {
          return (row*x+y);
}

void
printMatrix(int*arr, int row, int col) {
     for(int x = 0; x < row ; x++) {
             printf("\n");
             for (int y = 0; y <col ; y++) {
                 printf("%d  ",arr[getid(row, x,y)]);
             }
     }
}

main()
{

    int arr[2][2] = {11,12,21,22};
    int row = 2, col = 2;

    printMatrix((int*)arr, row, col);

}

来自这里

我也尝试过双指针.我还读到如果编译器不支持 VLA,还有一种不同的方法.我正在使用 gnu.

I also tried double pointers.I also read that there is a different approach if the compiler does not support VLAs. I am using gnu.

推荐答案

不完全确定,问题是什么,但它有效(并打印值9"):

Not exactly sure, what the problem is but this works (and prints the value "9"):

#include <stdio.h>

#define ROWS 10
#define COLUMNS 10

void func2(int multarray[][COLUMNS]){
        multarray[1][4]=10;
}

void func1(int multarray[][COLUMNS]){
        multarray[0][3]=9;
        func2(multarray);
}

int main(){

        int multarray[ROWS][COLUMNS];
        func1(multarray);
        printf("%d\n", multarray[0][3]);
        printf("%d\n", multarray[1][4]);
        return 0;
}

请注意,数组在传递给函数时会衰减为指针.

Notice, that the array decays to a pointer when passed to a function.

这篇关于在函数中操作多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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