Thread: Counting # of elements in array or file.

  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,897
    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, 04:27 PM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  3. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM