Page 1 of 1

Returning the size of an array problem.

Posted: Tue Nov 09, 2010 4:35 pm
by Exempt
Ok, I'm having trouble understanding why I get this outcome..

My array...

Code: Select all

int desX[] = {2730,2730,2730,2721,2728,2727,2720,2725,2728,2734,2730,2728,2730,2741,2738,2738,2732};
My function to get an arrays number of elements... takes te total size of the arrays memory uses then divides it by one element in the array.

This function only returns one.

Code: Select all

//Declaration is like this...
int length(int array[]);

//function call from my main is...just to test it.
cout<< length(desX);

//Get array length
int length(int array[])
{
    return (sizeof(array) / sizeof(array[0]));
}
Now if I do this I get a return of 17 which is what i need.

Code: Select all

cout<< sizeof(desX) / sizeof(desX[0]);

Re: Returning the size of an array problem.

Posted: Thu Nov 11, 2010 7:01 pm
by Administrator
You really can't pass arrays like you are doing. The proper way to do so in C/C++ is as follows:

Code: Select all

int someFunction(int *pArray, size_t len)
{
  for(unsigned int i = 0; i < len; i++)
  {
    cout << "Value: " << pArray[i] << std::endl;
  }
}

int anotherFunction()
{
  int array[] =  {1, 2, 3, 4, 5};
  size_t arrayLen = sizeof(array) / sizeof(int); // sizeof() on an array gives us the number of bytes, so divide by the size of the type to get the length.
  someFunction(array, arrayLen);
}

Re: Returning the size of an array problem.

Posted: Thu Nov 11, 2010 10:04 pm
by Exempt
I see, lol I haven't need arrays much. I guess i need to use themmore often.

Thanks.

Re: Returning the size of an array problem.

Posted: Fri Nov 12, 2010 7:17 pm
by Administrator
If you're using C++, I would suggest using std::vector instead. It's a bit 'easier' to work with.

Code: Select all

int function1(std::vector<int> &array)
{
  for(unsigned int i = 0; i < array.size(); i++)
    cout << array.at(i) << std::endl;
}

int function2()
{
  std::vector<int> array;
  array.push_back(1);
  array.push_back(2);
  array.push_back(3);

  function1(array);
}

Re: Returning the size of an array problem.

Posted: Sat Nov 13, 2010 8:03 pm
by Exempt
I don't really understand Vectors yet but i will check this out.