+ 7
How to know the number of element stored in this array? int arr[5]={1,2,4}; I mean which method should be used for.? In C++
12 Antworten
+ 4
size_t x = sizeof(arr) / sizeof(int);
That will give you the amount of elements in array, so long as you arent trying it on a function that only has a pointer to the array. (Anytime you pass an array into a function it is passed in as a pointer)
+ 7
Thx all @aklex & @Kirk
+ 7
Hi friend . (surprise) .. My Code is now public please see it. Include your name in it.
https://code.sololearn.com/cjNOwm9Q0vt3/?ref=app
+ 6
I believe you're supposed to keep track of this. The two unspecified elements will be initialized to 0. Since those zeroes might be exactly what you wanted (so...significant), as far as c++ is concerned, the array has 5 elements stored.
+ 6
@Kirk thanks,
Tell me then what is the method that should I used to know that this array has only 3 initialised element?
+ 6
Tell how to declare an int array with no initial size?
I mean is this valid :
int arr[] ;
+ 4
@I'm Muslim
int arr[];
"error: storage size of 'arr' isn't known"
@Robert's answer is the "allocate memory and point to it" approach, which arrives uninitialized and without sizeof() assistance [attempting sizeof on 'array' will instead return the size of the integer pointer].
Awesome followup there.
+ 3
You'd count any element that wasn't set to 0.
If 0 is significant, you have to initialize your array to a magic number (here, I use -1):
https://code.sololearn.com/cwifJUbLVM79/?ref=app
I show two methods to fill with a magic number:
std::fill_n(array, how many elements, value to set); // easy
memset(array, byte value, how many bytes) // because it's good to know
You could also initialize your magic constant with a plain loop.
+ 3
Here's one using @Rob Sommerer, MSc's method (I think I've got it right, though maybe not "best practice"...feedback welcome):
https://code.sololearn.com/cS6k3oZL1474/?ref=app
Shows uninitialized creation, initializing it, and counting set values (while keeping track of size).
+ 2
@aklex...that will always return 5 (the number of integers, regardless of whether they're set). Do you have a quicker way to check for non-zero (I'm just looping)?
+ 2
i would say that the non initialised elements would be 0 in a debug build,but random numbers in release builds. ALWAYS initialise variables. specially pointers (to nullptr). Of course there are situations where you could reason to not initialise i.e class members for performance in highly optimised programms like computer games.
be aware sizeof() operator only works for arrays on the stack. unfortunately for dynamically allocated arrays like int* array = new int[5]; this wouldn't work. you always need to keep track of its size and pass it along.
0
_countof (arr)