使用C ++中的函数来操作多维数组 [英] manipulating multidimensional arrays with functions in C++

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

问题描述

我试图使用函数修改C ++中的2D数组的内容。我找不到如何通过引用将2D数组传递给函数,然后操作单个单元格的信息。

I am trying to modify the contents of a 2D array in C++ using a function. I haven't been able to find information on how to pass a 2D array to a function by reference and then manipulate individual cells.

我想解决的问题以下格式。我已经做了一个简单的程序为了简洁。

The problem I am trying to solve has the following format. I have made a simple program for brevity.

#include<cstdlib>
#include<iostream>
using namespace std;

void func(int& mat) {
    int k,l;
    for(k=0;k<=2;k++) {
    for(l=0;l<=2;l++) {
    mat[k][l]=1;  //This is incorrect because mat is just a reference, but
                  // this is the kind of operation I want. 
    }
}

return; 
}

int main() {
int A[3][3];
int i, j;
char jnk;

for(i=0;i<=2;i++) {
    for(j=0;j<=2;j++) {
        A[i][j]=0;
    }
}

    func(A);

cout << A[0][0];
    return 0;
}

因此,A [0] [0]的值应从0 1.这是正确的方法是什么?非常感谢...

So the value of A[0][0] should change from 0 to 1. What is the correct way to do this? Many thanks in advance...

推荐答案

数组不通过值传递,所以你可以简单使用

Arrays are not passed by value, so you can simply use

void func(int mat[][3])

,如果你修改 mat 里面 func 的值, main

and, if you modify the values of mat inside func you are actually modifying it in main.

如果你知道矩阵的大小,具有指针:

You can use that approach if you know a priori the size of your matrix, otherwise consider working with pointers:

#include <iostream>

void f(int **m, int r, int c) {
    m[0][0]=1;
}

int main () {

    int **m;
    int r=10,c=10;
    int i;

    m = (int**)malloc(r*sizeof(int*));

    for (i=0; i<r;i++)
        m[i] = (int*)malloc(c*sizeof(int));

    f(m,r,c);

    printf("%d\n",m[0][0]);

    for(i=0;i<r;i++)
        free(m[i]);

    free(m);

    return 0;

}

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

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