GeeksforGeeks » C/C++ Programming Questions

Finding no. of elements in an integer array

(5 posts)
  1. k53
    Member
    Posted 3 months ago #

    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 NULL

    n=sizeof(arr)/sizeof(arr[0]);
    This gives the entire predefined size and not the no. of elements in it

  2. kartik
    Moderator
    Posted 3 months ago #

    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.

  3. k53
    Member
    Posted 3 months ago #

    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

  4. kartik
    Moderator
    Posted 3 months ago #

    @k53: you are right. My bad, no need to divide by size of an element.

  5. k53
    Member
    Posted 3 months ago #

    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.

RSS feed for this topic