I have a struct:
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
keysarray you can simply dosizeof(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 issizeof(keys[0]), which will return the size of the datatype ofkey[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