GeeksforGeeks » C/C++ Programming Questions
Finding no. of elements in an integer array
(5 posts)-
How to find the number of elements in an integer array ?
Cannot append NULL at the end and check for it bcoz the element 0 will be mistaken as NULLn=sizeof(arr)/sizeof(arr[0]);
This gives the entire predefined size and not the no. of elements in it -
Keep a variable to store address of the last element in array.
To get the number of elements, subtract address of first element from that of last element and divide the result by size of an element in array.
-
Thank you. But Dividing the difference by size of element gives undesired result.
I get the number of elements by just subtracting the address of first element from that of last element.
I guess it is so bcoz its similar to pointer arithmetic. Correct me if i'm wrong -
@k53: you are right. My bad, no need to divide by size of an element.
-
Thanks. Please consider this scenario
Sum of elements in an array has to be calculated using a function
Suppose the array has only 10 elements
I can use the function prototype like
int sum(int arr[50],int n);
where n is the number of elements in the array
Here can the sum be calculated without passing the number of elements to the function?
Reply
You must log in to post.