Nick Pampoukidis
Nick Pampoukidis

Reputation: 742

Passing 2d array c++

I'm trying to make a small program that swaps two columns and I have to use functions in order to do that but I just started on c++ and I cant get what I do wrong.

#include <iostream>

using namespace std;

int colSwap(int ng, int ns, int pin[][ns]) {
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 4; ++j) {
            cout << " i:" << i << " j:" << j << " " << pin[i][j] << " " << endl;
        }
        cout << endl;
    }
}

int main() {

    int ng = 3;
    int ns = 4;

    int pin[3][ns] = {{1, 2,  3,  4},
                     {5, 6,  7,  8},
                     {9, 10, 11, 12}};


    colSwap(ng,ns,pin);
    return 0;
}

I know that write it this way

int colSwap(int pin[][4]) {

}

but i need another method

Upvotes: 1

Views: 91

Answers (2)

AlphaRL
AlphaRL

Reputation: 1629

You can use template function

#include <iostream>

using namespace std;

template <size_t R, size_t C>
void colSwap(int(&arr)[R][C]) {
    for (int i = 0; i < R; ++i) {
        for (int j = 0; j < C; ++j) {
            cout << " i:" << i << " j:" << j << " " << arr[i][j] << " " << endl;
        }
        cout << endl;
    }
}

int main() {

    const int ng = 3;
    const int ns = 4;

    int pin[ng][ns] = {{1, 2,  3,  4},
        {5, 6,  7,  8},
        {9, 10, 11, 12}};


    colSwap(pin);
    return 0;
}

When declare an array, its size must be fixed, so ng and ns should be const int. The type of pin is actually int[3][4], you can just pass a reference of this type and let compiler deduce the size.

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409442

While it's possible to pass the sizes like that in C, it's not possible in C++. The reason being that C++ doesn't have variable-length arrays. Arrays in C++ must have its size fixed at the time of compilation. And no, making the size arguments const does not make them compile-time constants.

I recommend you use std::array (or possible std::vector) instead.

Upvotes: 5

Related Questions