How can get on the number of elements dynamic array

I declared the array in this way:

int *KeyValue=(int*)malloc(100*sizeof(int)); 

for(int i; ;){
     KeyValue[i] =  it->first * it->second ; u++;
   }

After using the KeyValue[] array I need to know the size of this array to used it in another place in my code.
I used something like this but this return just 1;
int sizeKeyValue =sizeof(KeyValue)/sizeof(KeyValue[0]);

How can I get the number of elements in dynamic array?

you specified it

You must remember it when creating an array.

Do not use "magic numbers" for size, use macros or constexpr for it:

so
int sizeKeyValue = KEY_ARRAY_SIZE;

1 Like

You know the size - because you defined it in the malloc call!

Instead of using a Magic Number like 100, make that a symbolic value that you can pass to these other places.

Or do you mean, how to know how many elements of the array have actually been "used" or "filled"?

To know that, you could:

  1. Keep a count as you use elements;
  2. Have a specific value to indicate the end of "used" data (as in C strings)

Do you mean that you want to know how many entries the array can hold or perhaps how many entries have been placed in the array ?

Either way the array size is not dynamic

But I did not use all the size, I used just 10. Is there any know the number of values in the dynamic array?

yes:

It seems an absolutely different problem rather than stated in the topic title.

1 Like

Yes, I mean that, I am asking is there any way to know the number of elements in the dynamic array without using a counter ?

It's not what you said!

You understand that the size of the array - ie, the amount of memory that it occupies - does not change?

Again, the number of elements does not change - it's just a matter of whether you've written anything to them or not

Yes - I gave you a 2nd way!

Can you give an example for the 2nd way please?

Now you can just loop through the array until you find an element containing EMPTY_VALUE.

You have to choose an EMPTY_VALUE that can never be used as an actual data value.

https://cplusplus.com/reference/cstring/memset/

1 Like

Thanks!

Maybe one of these Container Classes could help:

sizeof() is used at compilation time knowing that size of the variable that's been allocated.

what stops this loop from running forever?

It was probably meant as a sketch, i has not defined value.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.