Finding the size of an array

Jul 1, 2009 at 8:03am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
long     *values;

/* 
Synopsis:
int GetDataValues(long data_values[])

Arguments:
data_values[]
Array storing data values.
*/

if (GetDataValues(values) == 0) {
    cout<<"Error occured."<<endl;
    return;
}


for(int i=0; i< /*length of array values*/; i++)
cout<<values[i]<<endl;


How can I find out the length of the array values[] after a call to the function GetDataValues(values) so as to print out the individual elements of the array assigned in the GetDataValues method?
Jul 1, 2009 at 8:23am
Consider this example in which size of array "a" is stored in variable "size":
1
2
3
4
5
6
7
8
9
10
#include<iostream>
using namespace std;
int main()
{
    int a[]={1,2,3,4,5,6};
    int size;
    size=sizeof a/sizeof(int);      //total size of array/size of array data type
    cout<<size;                     
    return 0;
}


Jul 1, 2009 at 11:57am
But that doesn't really help in the case.

There are a couple of solutions, but the easiest is to return the number of elements from GetDataValues.

(More in the spirit of C++ would be to return say a vector<long> instead of an array.)
Jul 1, 2009 at 4:49pm
But that doesn't really help in the case.

There are a couple of solutions, but the easiest is to return the number of elements from GetDataValues.

(More in the spirit of C++ would be to return say a vector<long> instead of an array.)


At present the method GetDataValues is an existing method the API of an application. Therefore, GetDataValues is called to perform some data assignments for usage later. So I was wondering if I could know the length of the array assigned by GetDataValues. Thank you for your response.
Jul 1, 2009 at 5:14pm
Basically, if you are using an array you must pass the length.
Jul 1, 2009 at 5:38pm
To ronbutan: How can you declare an array without specifying its size directly or indirectly?
Tell me the whole problem you want to solve and also the whole code from upper left corner to lower right corner. I think your problem is not clear to answerable extent.
Last edited on Jul 1, 2009 at 5:53pm
Jul 1, 2009 at 5:50pm
You can't. How is the compiler supposed know how big to make the array unless you tell it?
Jul 1, 2009 at 7:32pm
I think your problem is not clear to answerable extent.


Agreed. The purpose of the getDataValues function is unclear. It requires the caller to give it an array and it returns an int. It appears that you want to pass it an uninitialized pointer. What will getDataValues do with the uninitialized pointer? Will it create some memory and dynamically allocate the array which the caller will be in charge of destroying? Perhaps it should simply return the number of elements in the array that it dynamically allocates.
Topic archived. No new replies allowed.