Reputation: 24705
What is the appropriate function that shows how many are there in an array?
int a[10];
a[0] = 1;
a[1] = 3;
So I want something that shows size of a = 2
.
Upvotes: 0
Views: 125
Reputation: 143
Oil Charlesworth seems to be right. The reason this is true is that when compiled a certain amount of memory is set aside (allocated) for that array no matter if it contains data or not. Therefore using a command like sizeof(a) will always yield the same result. It will return the amount of bytes allocated for your array. In this case the array is 40 bytes which makes sense because usually ints are 4 bytes long * length of the array (10) = 40.
This can differ from PC to PC though, at least, that's what I read in a tutorial a while back, the allocated size for each variable type seems to differ somewhat from PC to PC (or OS to OS).
Itś not much help, I know, but now you at least know why you can't do it with raw arrays.
Upvotes: 0
Reputation: 153840
This array has 10 elements. You just happened to assign two of them but this doesn't change the size of the areay. If you want simething to keep track of the elements you set use std::vector<int>
and push_back()
:
std::vector<int> array;
array.push_back(1);
array.push_back(3);
int size = array.size();
Upvotes: 1
Reputation: 55395
Sounds like you need a dynamically resizable array:
std::vector<int> a;
a.push_back(1);
a.push_back(3);
std::cout << a.size(); // 2
Upvotes: 1
Reputation: 272497
There is no way to do this with raw arrays.
Consider a container class instead, such as std::vector
:
std::vector<int> a;
a.push_back(1);
a.push_back(3);
std::cout << a.size() << "\n"; // Displays "2"
Upvotes: 3