Owen
Owen

Reputation: 4173

getting the number of elements in a struct

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.

Upvotes: 5

Views: 24216

Answers (6)

noname
noname

Reputation: 9

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.

Upvotes: 0

Luca Matteis
Luca Matteis

Reputation: 29267

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

Upvotes: 6

T33C
T33C

Reputation: 4429

sizeof(keys)/sizeof(*keys);

Upvotes: 3

robert
robert

Reputation: 34398

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.

Upvotes: 0

Naveen
Naveen

Reputation: 73433

You mean the count of elements in keys ? In such a case you can use int n = sizeof(keys)/sizeof(keys[0]);

Upvotes: 2

Alex Budovski
Alex Budovski

Reputation: 18436

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]))

Upvotes: 2

Related Questions