Returning the size of an array problem.

Ask questions about cheating in any games you would like. Does not need to pertain to MicroMacro.
Post Reply
Message
Author
Exempt
Posts: 197
Joined: Wed Jan 20, 2010 9:55 am

Returning the size of an array problem.

#1 Post by Exempt » Tue Nov 09, 2010 4:35 pm

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]);

User avatar
Administrator
Site Admin
Posts: 5306
Joined: Sat Jan 05, 2008 4:21 pm

Re: Returning the size of an array problem.

#2 Post by Administrator » Thu Nov 11, 2010 7:01 pm

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);
}

Exempt
Posts: 197
Joined: Wed Jan 20, 2010 9:55 am

Re: Returning the size of an array problem.

#3 Post by Exempt » Thu Nov 11, 2010 10:04 pm

I see, lol I haven't need arrays much. I guess i need to use themmore often.

Thanks.

User avatar
Administrator
Site Admin
Posts: 5306
Joined: Sat Jan 05, 2008 4:21 pm

Re: Returning the size of an array problem.

#4 Post by Administrator » Fri Nov 12, 2010 7:17 pm

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);
}

Exempt
Posts: 197
Joined: Wed Jan 20, 2010 9:55 am

Re: Returning the size of an array problem.

#5 Post by Exempt » Sat Nov 13, 2010 8:03 pm

I don't really understand Vectors yet but i will check this out.

Post Reply

Who is online

Users browsing this forum: No registered users and 5 guests