How to create array with size of another method returning value

Hi,
I have to create array with size that returns from method

int val=test();
int arr[val];

int test()
{
// Some logic and getting result as 5

return 5;
}

I would like to create arr with 5. could anyone please guide me how can i do this.
You need to use new to create array dynamically, like this:
int* array = new int[10];

ps. dont forget to use delete [] afterwards
hi, thanks for reply. This can be done, but if i get size of array by "sizeof(arr)/sizeof(&arr[0])", i'm getting 1, but not 10. How to get arr size as 10 ?
Is there a reason it has to be complicated by arrays when you can use a vector?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <vector>
#include <iostream>

int test()
{
    return 5;
}

int main()
{
    int val=test();
    std::vector<int> arr(val);
    std::cout << "The size of arr is " << arr.size() << '\n';
}

sizeof is executed in compile time and you are allocating memory in run-time.

sizeof return size in bytes. sizeof(arr) which is int is 4 bytes. sizeof(&arr[0]) is int address which is 4 bytes too.

You have wrong understanding of what sizeof do.

sizeof(arr) which is int is 4 bytes.

Actually, no. arr is not an int, it's a pointer to an int, i.e. an address. The name of an array is always a pointer to the first element of the array.

It's still 4 bytes though :)

To the OP: Cubbi is right. You should use vectors rather than C-style arrays, unless you have a very good reason for using the array.
Last edited on
Hi, Thanks Cubbi. I got your point and i'll replace with Vector everywhere. But i have small query that i almost deal with more arrays, so if i replace everything with Vector , will that affect performance ?.

example :
Totally i'm developing algorithm. so right now my algorithm accepts 5 array parameter. if replace with Vector, its dependencies also i need to change to vector. so will that affect algorithm performance, ( data may deal with 40 crore records )
well, using STL mostly will affect performance if you don't know how to use it, vector has this problem:
a vector is allocated in a contiguous memory, so if you extend the vector it might need to reallocate all its data, that is bad for performance.
vector is good if you don't need to extend it often.
Last edited on
Topic archived. No new replies allowed.