Thread: length of dynamic array

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    74

    length of dynamic array

    how do I get the length (or size) of a dynamic array? tried this but I get 0

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    typedef struct a
    {
    	int age;
    	char name[10];
    } el;
    
    int main (int argc, const char * argv[]) 
    {
    	int i,n;
    	el *array;
    	int d;
    
    	printf("length :> ");
    	scanf("%d",&n);	
    
    	array = (el *) calloc (n,sizeof(el));
    
    	
    
    
    	printf("\nINPUT\n\n");
    	for (i=0; i<n; i++)
    	{
    			printf("name %d. el :> ",i);
    			scanf("%s", array[i]. name);
    			printf("age %d. el :> ",i);
    			scanf("%d",& array[i]. age);
    	}
    	
    	printf("\nPRINTOUT\n\n");
    	for (i=0; i<n; i++)
    	{
    			printf("%d. el :> NAME:\t%s\tAGE:\t%d\n",i, array[i]. name, array[i]. age);		
    	}	
    	
    	d =  sizeof(array)/sizeof(el);
    	
    					printf("Length is :> %d",d);
    
    	return 0;
    }
    Last edited by budala; 09-02-2009 at 03:48 AM.

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Variable n is not initialized. The value of n * sizeof(el) will be how large array is - you have to keep track of that.
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Code:
    d =  sizeof(array)/sizeof(el);
    This will not work since sizeof(array) is just the size of a pointer on your machine (probably 4 or 8 bytes depending on your CPU architecture). As Dino said, the only way to get the size is to use what you passed to calloc() or malloc().
    bit∙hub [bit-huhb] n. A source and destination for information.

  4. #4
    Registered User
    Join Date
    Apr 2009
    Posts
    74
    oops, I changed the order of instructions red and blue.

    I don't want to keep track of the size, I want to have a dynamic array and calculate its size

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I'll put it in simple words:
    There is no (standard) way to calculate the length of a dynamic array in C.

    If you really, really, really, really must do it, there are non-portable solutions.
    Microsoft's compilers gives you the option of _msize.
    Then you could use the OS's allocation APIs to allocate and find the size of it.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by budala View Post
    oops, I changed the order of instructions red and blue.

    I don't want to keep track of the size, I want to have a dynamic array and calculate its size
    You can't calculate the size of a malloc'ed piece of memory (unless you get your hands dirty with the grubby internals of malloc, but then that will only work on that one particular system). The whole point of malloc is that you know what you called it with.

  7. #7
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Quote Originally Posted by budala View Post
    oops, I changed the order of instructions red and blue.

    I don't want to keep track of the size, I want to have a dynamic array and calculate its size
    If it would work of what you have in mind you could put an ending character to enable you to calculate its size.
    In most cases tracking the size would be the best way though. Since it is easy and the extra calculations not time consuming compared to malloc().
    If you plan on using malloc (or realloc) a lot of times and are afraid you might miss an update of its size you could wrap "the keep track of size" code and malloc in a single function

  8. #8
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Another option is to store the size information in the data itself.

    Code:
    #include <stdlib.h>
    
    size_t* b_element_size_ptr_( void* buf )
    {
        return ( size_t* )( ( char* )buf - sizeof( size_t ) );
    }
    
    size_t* b_length_ptr_( void* buf )
    {
        return ( size_t* )( ( char* )buf - ( sizeof( size_t ) << 1 ) );
    }
    
    void* b_allocate( size_t siz, size_t len )
    {
        char*
            buf = malloc( siz * len + ( sizeof( size_t ) << 1 ) );
        if( buf )
        {
            buf += sizeof( size_t ) << 1;
            *b_element_size_ptr_( buf ) = siz;
            *b_length_ptr_( buf ) = len;
        }
        return buf;
    }
    
    void b_deallocate( void* buf )
    {
        if( buf )
            free( b_length_ptr_( buf ) );
    }
    
    size_t b_length( void* buf )
    {
        return *b_length_ptr_( buf );
    }
    
    size_t b_bytes( void* buf )
    {
        return b_length( buf ) * *b_element_size_ptr_( buf );
    }
    Example:

    Code:
    #include <stdio.h>
    
    int main( void )
    {
        int*
            data = b_allocate( sizeof( int ), 1024 );
        if( data )
        {
            printf( "Length of data: %d\n", b_length( data ) );
            printf( "Size (in bytes): %d\n", b_bytes( data ) );
        }
        b_deallocate( data );
        return 0;
    }
    Last edited by Sebastiani; 09-02-2009 at 09:53 AM.

  9. #9
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    There's probably some OS specific system call you could make prior to the malloc, to determine your process's free memory, and then you could call it again after the malloc, and figure out the difference.

    Sounds like a contrived class exercise to me.
    Mainframe assembler programmer by trade. C coder when I can.

  10. #10
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by Dino View Post
    There's probably some OS specific system call you could make prior to the malloc, to determine your process's free memory, and then you could call it again after the malloc, and figure out the difference.

    Sounds like a contrived class exercise to me.
    Except, at that point you obviously know how large the block is going to be.

  11. #11
    Registered User
    Join Date
    Feb 2011
    Posts
    96
    Quote Originally Posted by Dino View Post
    . . .
    Sounds like a contrived class exercise to me.
    He he, you could call it that - it's my own research though and for practical application if I can ever get them dang pointers figured out.

    As far as the indexOf and strReplaceAll go, I really do need those functions pretty badly and a few more like them.
    I'm running in C# and I'm just sick of the lame performance.
    I'm pretty near convinced that if I can write funcs in C instead of using the C# funcs I'll improve my performance dramatically.

    Salem has me convinced that my biggest problem is, I don't understand memory allocation (no matter what the language). If I could understand what's really going on 'under the covers' for us 'managed code' guys, it'd help a great deal with performance. I've been dodging pointers, memory allocation and garbage collection for a *long* time.

    Performance has never been a major issue for me till lately, I find myself dealing with large quantities of data these days.

    I've been a full time programmer (mostly business/small business - database/internet) 15 years and I'm still learning . . .

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    This is just me thinking out loud... but perhaps you should just get a book on C and start with chapter 1 ... of course you will go through parts of it pretty quickly... but at least then you'll have all the required information...

    In deference to Salem's obvious smarts... In this case I might suggest that your real problem is that you're trying to understand C as some sort of mystical subset of C# ... Believe me the language similarities are completely absent beyond the totally disastrous choices of names. If the big guns had been smart they would have followed their predicessor's lead and moved up the alphabet C++ would be E (D already existed) and when they got to C# they would have said "Oh F it"...

    Learn C ... don't try to learn C as it applies to C#... Just learn the language on it's own merrits.
    Last edited by CommonTater; 02-12-2011 at 02:27 PM.

  13. #13
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    I like Sebastiani approach.
    But he left out b_realloc()

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Array
    By firetheGlazer in forum C Programming
    Replies: 4
    Last Post: 07-11-2008, 11:57 AM
  2. the length of my array is not what I expected
    By luca in forum C Programming
    Replies: 7
    Last Post: 12-05-2006, 03:14 AM
  3. Checking maximum values for dynamic array...
    By AssistMe in forum C Programming
    Replies: 1
    Last Post: 03-21-2005, 12:39 AM
  4. Dynamic 2d array
    By Mithoric in forum C++ Programming
    Replies: 8
    Last Post: 12-29-2003, 09:19 AM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM

Tags for this Thread