1

I have to add new features to old code. The old code have a problem, there are lot of functions which gets arrays as argument, something like this f(int x[][MAX_LENGTH]). So I wan't to ask is it ok (standard) to pass int *[MAX_LENGTH] instead? In other words is the code bellow standart?

# include <iostream>
using namespace std;

void f(int x[][3])
{
    for(int i = 0; i < 2; ++i)
    {
        for(int j = 0; j < 3; ++j)
            cout << x[i][j] << " ";
        cout << endl;
    }
}

int main()
{
    typedef int v3 [3];
    v3 *x;
    x = new v3 [2];
    for(int i = 0; i < 2; ++i)
        for(int j = 0; j < 3; ++j)
            x[i][j] = i * 3 + j; 

    f(x);

    delete [] x;
    return 0;
}

edit please point the paragraph of standard document if the answer of the question is "YES".

Mihran Hovsepyan
  • 10,810
  • 14
  • 61
  • 111

2 Answers2

2

The compiler rewrites f(int x[][MAX_LENGTH]) as f(int (*x)[MAX_LENGTH]) which is different from f(int *x[MAX_LENGTH]). The former is a pointer to an array, the latter is an array of pointers.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • However, in the example the type of `x` really is `int (*)[3]`. So the example is correct - it doesn't even require a conversion on function argument `x`. – aschepler May 10 '11 at 12:42
  • @asch: Mihran was specifically asking if he could rewrite the parameter as `int *[MAX_LENGTH]`. My answer is no, because that would change the semantics. – fredoverflow May 10 '11 at 12:45
1

Your question doesn't match your code, x in main has type int (*)[3], not int *[3]. In this instance the parentheses are important becuase the first is a pointer to an array and the second is an array of pointers.

Your function call f(x) is valid because your function declaration is equivalent to

void f(int (*x)[3])

Function parameters declared as arrays are converted to the equivalent pointer type. (ISO/IEC 14882:2003 8.3.5 [dcl.fct] / 3 )

x in main has type v3*, which expanding the typedef is int (*)[3] which is exactly the type required by f.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656