size of dynamic array

This is a discussion on size of dynamic array within the C Programming forums, part of the General Programming Boards category; I always thought that the size of a dynamic array had to be passed around, and that it couldn't be ...

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    245

    size of dynamic array

    I always thought that the size of a dynamic array had to be passed around, and that it couldn't be determined by looping through the array.

    In this project I'm working on, there's bit of code:
    Code:
    extern char *
    create_spec(DescList *input_lists, char *function)
    {
        int list_count = 0;
        int l, i;
        char *str;
        while(input_lists && input_lists[list_count] != NULL)
        {
             list_count++;
        }
         ....
        ....
    }
    How does this NOT segfault? I thought if you went passed the bounds of an array (dynamic or static), it segfaults?

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    245
    I see what's going on. They append NULL to the end of DescList array (after creating it), so that allows them to determine the size - 1.

  3. #3
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,160
    Quote Originally Posted by dayalsoap View Post
    I see what's going on. They append NULL to the end of DescList array (after creating it), so that allows them to determine the size - 1.
    Same way strings work.

    It's pretty common to terminate an array of items with some kind of sentinel value.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  4. #4
    Password:
    Join Date
    Dec 2009
    Location
    NC
    Posts
    587
    It will segv if null is passed as input_lists, do this to short-circuit:
    Code:
    while(input_lists != NULL && input_lists[list_count] != 0)
    {
        list_count++;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. Dynamic Array Allocation function
    By P4R4N01D in forum C++ Programming
    Replies: 6
    Last Post: 05-15-2009, 02:04 AM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  4. size of dynamic array
    By tommy_gunn in forum C Programming
    Replies: 3
    Last Post: 12-30-2004, 07:01 PM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM

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