Thread: burchasergin

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    80

    Post memry allocation

    for example i enter an string lenght is n.how can i take space from memory for that string
    for example my array is word[32] but my name has 4 characters
    the rest of this array dont be used. how can i prevent this?
    Last edited by condorx; 05-24-2002 at 01:28 PM.

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    By allocating memory dynamically.

    Code:
    char *word;
    int length;
    
    length = .... <determine length here or get it from somewhere>..;
    
    /* Create a dynamic array */
    word = malloc (sizeof (char) * length);
    
    ..... <do some stuff with word> ...
    
    /* Release the allocated memory */
    free (word);
    If I remember well, C99 supports dynamical arrays in this way:

    Code:
    void function (int length)
    {
        char word [length];
         
        ... <some stuff> ...
    }

  3. #3
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669
    By the way, what is C99?
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  4. #4
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    C99 is the code of the latest C standard, ISO/IEC 9899:1999.

  5. #5
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669
    Does VC++.NET support this standard?
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  6. #6
    Registered User
    Join Date
    Feb 2002
    Posts
    589
    They claim they do but no compiler conforms 100%

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by Shiro
    By allocating memory dynamically.

    Code:
    char *word;
    int length;
    
    length = .... <determine length here or get it from somewhere>..;
    
    /* Create a dynamic array */
    word = malloc (sizeof (char) * length);
    
    ..... <do some stuff with word> ...
    
    /* Release the allocated memory */
    free (word);
    Close, but no cigar. This is a "Bad Thing(TM)". You fail to allocate enough space for the null terminator (unless you've included that in your "lenght" count).

    word = malloc( sizeof(char) * (length + 1) );
    word[length] = '\0';

    Now it's safe to use. (Actually you may want to memset it, but that's optional.)

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed