Finding the size of an array

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


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.)
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.
Basically, if you are using an array you must pass the length.
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
You can't. How is the compiler supposed know how big to make the array unless you tell it?
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.