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

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

问题描述

我在这里读了很多的东西,尝试了很多,但我无法找到一个方法来传递一个多维数组在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.

我想找到一种方法,将数组传递给function.Then从第一功能,第二个通过它,做一些有(也许打印,也许改变的值),然后再使用它来第一个函数最后使用数组中的主力。

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;
}

我也试过这样的:

I also tried this:

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

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

我也试过这样的:

I also tried this:

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);

}

我也试过双pointers.I也看到有一种不同的方法,如果编译器不支持沃拉斯。我使用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天全站免登陆