+ 4
(C/C++) Is it a logical way to give the size of an array from the user?
15 Respuestas
+ 2
C++ standard doesn't allow it. The size must be known at compile time. SoloLearn uses gnu compiler, which accepts it. Personally, I think it is good thing, but most discussions I've read on the subject disagree.
+ 5
@mohammed I know how to do it
I’m wondering if there’s no problem to do in this way cause i’ve read an article about it and it says it will capture more than that size from the memory and it will effect on the speed of run then. I don’t know if it’s true. That’s why I asked.
+ 5
Thank you guys. 👍
+ 4
@shobhit won’t it have bad effects on the speed of programs?
+ 4
it will have but suppose you know that size of array < 1000001 then you can. Because you may to do it otherwise as well.
Abstain from doing it if not required.
+ 4
Answers given above look rather theoretical. I see the question from more practical position. There's no such practical task as just 'allocate RAM of this size'. Array is memory resource abstraction. In real life you MUST CONTROL RESOURCES you code uses so idea to allocate any resource without handling it's availability is WRONG. Code must survive most real conditions if It's not engeneered for dedicated hardware. User has no idea on memory available so it's coder's responsibility to handle resources. From this practical point of view it's not 'logical', isn't it?
+ 3
dp u mean something like this
https://code.sololearn.com/cCdBQCXo3Y7k/?ref=app
+ 3
@shobhit exactly
+ 3
@alizafar as john mentioned sometimes when compiler(other than gnu) doesn't allow the size of array to defined at runtime, you can the declare the array with a number that is bigger than what you may encounter. Something like this
arr[1000001];
+ 3
yep! this was my first problem while learning arrays in c++
0
The cost of gnu doing it for you is cheaper than using the Array template, which people defending the standard suggest using to achieve the result. The compiler allocates a pointer and all usages have the cost of deferencing that pointer. It location isn't something I've looked up as yet. I suspect it is on the heap and allocated via new as that would be the easiest for the compiler to generate code for.
0
Which is obsolete as 2003, 2011, & 2017 standards replaced it.
0
you can make the loop time like if user enter my array size should be 5 then you can follow this...
for(i=0;i<n;i++)
{
cin<<a[i];
}