-2

The below program compiles and runs correctly, but the value 5 in int sum(int p[5][30][20],int n) is ignored, why?

int sum(int p[5][30][20],int n)
{
    int s=0;
    for(int i=0; i<n; i++)
    for(int j=0; i<30; j++)
    for(int k=0; i<20; k++)
    s+=p[i][j][k];
    return s;
}

...
int x[40][30][20];
int s=sum(x,40);

In the function, it is int p[5][30][20], but for the function call, x[40][30][20] is used, yet it works.

I appreciate if help me to interpret it.

Arun A S
  • 6,421
  • 4
  • 29
  • 43
Ebrahim Ghasemi
  • 5,850
  • 10
  • 52
  • 113

1 Answers1

2

The outermost loop in the function

int sum(int p[5][30][20],int n)
{
    int s=0;
    for(int i=0; i<n; i++)
    for(int j=0; i<30; j++)
    for(int k=0; i<20; k++)
    s+=p[i][j][k];
    return s;
}

iterates from 0 to n where n as it follows from the function call

int s=sum(x,40);

is equal to 40.

When an array is passed to a function by value it is implicitly converted to pointer to its first element. So these function declarations

int sum( int p[5][30][20],int n);
int sum( int p[40][30][20],int n);
int sum( int p[][30][20],int n);
int sum( int ( *p )[30][20],int n);

are equivalent and declare the same one function.

You may use all these four declarations simultaneously in your program. Though the function itself shall be defined only once.

For example

int sum( int p[5][30][20],int n);
int sum( int p[40][30][20],int n);
int sum( int p[][30][20],int n);
int sum( int ( *p )[30][20],int n);

int sum(int p[1000][30][20],int n)
{
    int s=0;
    for(int i=0; i<n; i++)
    for(int j=0; i<30; j++)
    for(int k=0; i<20; k++)
    s+=p[i][j][k];
    return s;
}

Within the function p is a pointer that points to an object of type int [30][20] (first element of the original array)

A different situation occurs when an array is passed by reference. For example if your function is declared like

int sum(int ( &p )[5][30][20] );

then the compiler will issue an error for the call

int s=sum(x);

because the type of x differs from the array type of the function parameter.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335