3 Replies - 523 Views - Last Post: 02 February 2011 - 01:12 PM Rate Topic: -----

#1 log3337  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 73
  • 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.

if i hade this array:

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  Icon User is online

  • #include "soul.h"
  • member icon

Reputation: 1138
  • View blog
  • Posts: 7,110
  • 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.
Was This Post Helpful? 0
  • +
  • -

#3 ishkabible  Icon User is offline

  • spelling expret
  • member icon




Reputation: 1622
  • View blog
  • Posts: 5,709
  • 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
Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6039
  • View blog
  • Posts: 23,436
  • 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;
}

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1