I have a struct:
开发者_C百科struct KeyPair
{
int nNum;
string str;
};
Let's say I initialize my struct:
KeyPair keys[] = {{0, "tester"},
{2, "yadah"},
{0, "tester"}
};
I would be creating several instantiations of the struct with different sizes. So for me to be able to use it in a loop and read it's contents, I have to get the number of elements in a struct. How do I get the number of elements in the struct? In this example I should be getting 3 since I initialized 3 pairs.
If you're trying to calculate the number of elements of the keys
array you can simply do sizeof(keys)/sizeof(keys[0])
.
The point is that the result of sizeof(keys)
is the size in bytes of the keys array in memory. This is not the same as the number of elements of the array, unless the elements are 1 byte long. To get the number of elements you need to divide the number of bytes by the size of the element type which is sizeof(keys[0])
, which will return the size of the datatype of key[0]
.
The important difference here is to understand that sizeof()
behaves differently with arrays and datatypes. You can combine the both to achieve what you need.
http://en.wikipedia.org/wiki/Sizeof#Using_sizeof_with_arrays
sizeof(keys)/sizeof(*keys);
If you're trying to count the elements of the array, you can make a macro
#define NUM_OF(x) (sizeof(x)/sizeof(x[0]))
You mean the count of elements in keys
? In such a case you can use int n = sizeof(keys)/sizeof(keys[0]);
In C++ it is generally not possible to do this. I suggest using std::vector.
The other solutions work in your specific case, but must be done at compile time. Arrays you new or malloc will not be able to use those tricks.
If you're trying to calculate the number of elements of the keys array you can simply do sizeof(keys)/sizeof(keys[0]).
This can not be a general good solution, due to structure padding.
精彩评论