1

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

Nick Pampoukidis
  • 702
  • 8
  • 28
  • You cannot reference another parameter to determine the size. Write `int colSwap(int ng, int ns, int** pin) {` instead. – πάντα ῥεῖ May 23 '16 at 14:43
  • 1
    @πάνταῥεῖ Except that an [array of arrays is really not the same as a point to pointer](http://stackoverflow.com/questions/18440205/casting-void-to-2d-array-of-int-c/18440456#18440456). – Some programmer dude May 23 '16 at 14:45

2 Answers2

5

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

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.

Shangtong Zhang
  • 1,579
  • 1
  • 11
  • 18