0

In this code why output is always 12, irrespective of value of n.

include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> arr(n); for(int arr_i = 0; arr_i < n; arr_i++){ cin >> arr[arr_i]; } cout<<sizeof(arr)<<endl; return 0; }

27th Feb 2018, 3:04 PM
SANGMESH PATIL
SANGMESH PATIL - avatar
3 Respostas
+ 3
sizeof() by default returns the size of the object of type vector, and that may have a fixed size of 12 bytes. So to get the number of elements or the maximum current capacity, use size() or capacity(). Eg : cout<<vec.size()<<endl; Also, visit : https://stackoverflow.com/questions/2373189/sizeof-a-vector
27th Feb 2018, 3:22 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
sizeof is known at compile time. It is how many bytes an object takes on the stack. But the data of a vector is on the heap. To get the vectors size, use arr.size().
27th Feb 2018, 3:25 PM
Timon Paßlick