+ 2
Is there a way to find how many elements are inside a array
int z; cin>>z; int arr[z]; for (int x=0;x < /****/;x++){ //statements; } how can i get how many elements arr has without using z ?
11 Answers
+ 2
int arrsize = sizeof(arr) / sizeof(arr[0]);
cout<<arrsize<<endl;
+ 3
wouldn't the number of elements here just be the value in z?
+ 3
hinanawi a way without using z
+ 2
Shahil Ahmed in that case, it's what SagaTheGreat said
+ 2
SagaTheGreat sizeof is a compile time operator so that solution shouldn‘t work, since the size of the array is not know at compile time
+ 2
Max works on here, although it might be undefined behavior
+ 2
here is another way:
https://code.sololearn.com/c5aCop4kMlc0/#cpp
+ 1
Max try this,
include <iostream>
using namespace std;
int main() {
int z = 0;
cin>>z;
int arr[z];
cout<< (sizeof(arr)/sizeof(arr[0]))<<endl;
return 0;
}
It is working. sizeof was compile time operator in 89 from 99 it is runtime operator.
+ 1
SagaTheGreat in c you are right but as far as i know it still is compile time in c++. the standard says the following: "The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id. The sizeof operator shall not be applied to an expression that has function or incomplete type, to an enumeration type whose underlying type is not fixed before all its enumerators have been declared, to an array of runtime bound, ..." . note that is says that it should not be applied to an array of runtime bound
+ 1
Max
Right, sizeof operator is evaluated runtime for cpp.
Then how my trail comment code is working.
Do you know ? I know that due to compiler optimization.
cin>>z;
int arr[z];
cout<< (sizeof(arr)/sizeof(arr[0]))<<endl;
so In above code z has some value at runtime. but from int arr[z] compiler knows array is of int type. so at compiler time compile use below expression and it is resolved at run time when z has some value.
sizeof(arr) = sizeof(int) * z
sizeof(arr[0]) = sizeof(int)
now compiler knows sizeof(int).let's say for 32 bit compiler int size is of 4 bytes.
then over all cout expression after comiplation will be look like,
cout<<(4*z)/4<<endl;
hence it is working.
+ 1
SagaTheGreat i never said that it wouldn‘t work
i just said that its not in the standard and that you can therefore not expect it to work in every compiler or even across compiler versions
or for more complex code, so one day in the future Shahil Ahmed will try to use your trick for something more complicated and it wont compile or give him weird results