Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 481
Owen Avatar asked Dec 17 '22 19:12

Owen


1 Answers

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

like image 184
Luca Matteis Avatar answered Dec 30 '22 20:12

Luca Matteis