Function to return number of values in an array

Page 1 of 1

3 Replies - 807 Views - Last Post: 02 February 2011 - 01:12 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=213606&amp;s=f7c8df40dcba2f81854760fb08f7cb76&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 log3337

Reputation: 0
• Posts: 77
• Joined: 22-July 09

Function to return number of values in an array

Posted 02 February 2011 - 11:07 AM

Hi everybody!

I am making a program that can do synthetic division of polynomials for math class, and i am doing this with arrays.

```int hi;
cin >> hi;
int hello [hi];

```

is there a function that exists that returns that value hi? that returns the number of elements in an array?

thanks
Is This A Good Question/Topic? 0

Replies To: Function to return number of values in an array

#2 BetaWar

• #include "soul.h"

Reputation: 1307
• Posts: 7,678
• Joined: 07-September 06

Re: Function to return number of values in an array

Posted 02 February 2011 - 11:29 AM

No, not with arrays. An array is just a pointer to a block of memory, meaning that it only stores what you put in it and nothing else.

However, since you are using C++ you could use the vector class, which does store the size of the array it is maintaining for you and even has a simple function call to get that value.

#3 ishkabible

• spelling expret

Reputation: 1676
• Posts: 5,836
• Joined: 03-August 09

Re: Function to return number of values in an array

Posted 02 February 2011 - 11:30 AM

no you have to keep track of the size of the array your self. a clean solution is to use std::vector or std::deque. they allow you to use dynamically sized arrays and not have to worry about allocation and the size of the array as the size() method allows you to get the size at any time. also they are extremely well optimized which is a big bonus. here take a look at this

• Saucy!

Reputation: 6219
• Posts: 23,965
• Joined: 23-August 08

Re: Function to return number of values in an array

Posted 02 February 2011 - 01:12 PM

```#include <iostream>

int main()
{
// Variable to store the size of the array
int numElements = 0;

// Get number of elements to put into the array
cin >> numElements;

// Allocate the array
int *arrayOfInts = new int[numElements];

// Get input
int i = 0;
for (; i < numElements; ++i)
cin >> arrayOfInts[i];

// Print values in array
for (i = 0; i < numElements; ++i)
cout << "Element " << i + 1 << " " << arrayOfInts[i] << endl;

// Deallocate memory for array
delete [] arrayOfInts;

return 0;
}
```