Counting # of elements in array or file.

This is a discussion on Counting # of elements in array or file. within the C Programming forums, part of the General Programming Boards category; One of the functions in my program needs to count the elements of an array or data file for use ...

  1. #1
    Unregistered
    Guest

    Counting # of elements in array or file.

    One of the functions in my program needs to count the elements of an array or data file for use in computing an average of the elements sum. How might I go about getting this number for a function?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    The following will only work on arrays where the last element is a null character.
    Code:
    int countArray(char *array){
        int n = 0;
        while(array[n] != '\0')
            n++;
    
        return n;
    }
    However, in a well designed system you should always know the size of your arrays, be it by defining a constant to set the base size or keeping a counter for a dynamic array. That number - 1 would be the actual length of the array.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 05:27 PM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 04:44 PM
  3. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 04:39 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 10:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21