Hi,

I am having an issue with a program and I have ended up realizing I don't know how to pass an array as a parameter.

It seems that when I do it the arrays length is one inside of the function, even though outside is different.

Here is the code

include <iostream>

using namespace std;

#define length(x) (sizeof(x)/sizeof(x[0]))

int maximo(int v[])
{
  int result = 0;
  int tamano;


  tamano = length(v);
  cout << "length = " << tamano << endl;
  for(int i=0; i<tamano; i++) {
    if (v[i] > result)
      {
	result = v[i];
      }
  }
  return result;
}


int main () {
  int a1[5] = {0};
  int a2[] = {2,3,4};
  int a3[4] = {1, 21, 2 ,8};
  
  cout << "array length " << length(a1) << " and the max is: " << maximo(a1) << endl;
  cout << "array length " << length(a2) << " and the max is: " << maximo(a2) << endl;
  cout << "array length " << length(a3) << " and the max is: " << maximo(a3) << endl;
  
  return 0;
}

The function only tries tu return the maximum of an array of integers. The output is as follows:

length = 1
array length 5 and the max is: 0
length = 1
array length 3 and the max is: 2
length = 1
array length 4 and the max is: 1

I am a bit lost with this and I don't find the solution in the internet (I must be searching bad)

Thanks!

You need to pass the size as well as the array. That's the only way the function knows how big the array is.

>> tamano = length(v);

That line does not do what you think it does. The array passed in
as a parameter gets converted to a pointer, essentially. When that
happens, the size of the array is lost. You can either pass in the size( as suggested by WaltP) or you can use template deduction to let
the compiler deduce the size.

Edited 6 Years Ago by firstPerson: n/a

This article has been dead for over six months. Start a new discussion instead.