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?
b707
July 18, 2023, 12:06pm
3
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
awneil
July 18, 2023, 12:07pm
4
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:
Keep a count as you use elements;
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?
b707
July 18, 2023, 12:09pm
8
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 ?
awneil
July 18, 2023, 12:18pm
10
mercala_eng:
Yes, I mean that
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?
awneil
July 18, 2023, 12:27pm
13
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
awneil
July 18, 2023, 12:30pm
15
Maybe one of these Container Classes could help:
C++ container-like classes (vector, map, etc.) for Arduino which cannot use STL - GitHub - hideakitai/ArxContainer: C++ container-like classes (vector, map, etc.) for Arduino which cannot use STL
gcjr
July 18, 2023, 12:53pm
16
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.
system
Closed
January 14, 2024, 2:06pm
18
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.