Getting the number of elements in a structure

I have a structure:

struct KeyPair 
{ 
   int nNum;
   string str;  
};

Let's say I initialize my structure:

 KeyPair keys[] = {{0, "tester"}, 
                   {2, "yadah"}, 
                   {0, "tester"}
                  }; 

I would create several instances of the structure with different sizes. Therefore, in order for me to use it in a loop and read its contents, I need to get the number of elements in the structure. How to get the number of elements in the structure? In this example, I should get 3, since I initialized 3 pairs.

+3
source share
6 answers

If you are trying to calculate the number of elements in an array keys, you can just do sizeof(keys)/sizeof(keys[0]).

, sizeof(keys) . , , 1 . , , sizeof(keys[0]), key[0].

, sizeof() - . , , .

http://en.wikipedia.org/wiki/Sizeof#Using_sizeof_with_arrays

+4
sizeof(keys)/sizeof(*keys);
+2

,

#define NUM_OF(x) (sizeof(x)/sizeof(x[0]))
+1

keys? int n = sizeof(keys)/sizeof(keys[0]);

+1

In C ++, this is generally not possible. I suggest using std :: vector.

Other solutions work in your specific case, but must be executed at compile time. Arrays that you are new or malloc will not be able to use these tricks.

0
source

If you are trying to calculate the number of elements in a key array, you can simply do sizeof (keys) / sizeof (keys [0]).

This may not be a general good decision due to the filling of the structure.

0
source

Source: https://habr.com/ru/post/1776861/


All Articles