Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

manipulating multidimensional arrays with functions in C++

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

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

void func(int mat[][3])

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
",m[0][0]);

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

    free(m);

    return 0;

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...