Thread: inserting values in an array

  1. #1
    Registered User
    Join Date
    Sep 2007
    Location
    somewhere out there
    Posts
    7

    inserting values in an array

    hi how can i insert a value in an array?
    i want to insert an element to an array..
    in php it can be done with this..
    Code:
    $arrayname[] .= $value;
    how about in c?
    thanks
    Last edited by fairyjerry14; 10-12-2007 at 12:34 AM.

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    If it's on the stack you can't.

    you'd have to resize it (providing it was allocated on the heap).

    Code:
    char * arr = NULL;
    size_t elements = 10;
    
    if((arr = malloc(elements * sizeof(char))) == NULL)
    {
        /* error, exit */
        
    }
    
    
    /* set the array values, oops we need 11 elements */
    
    if((arr = realloc(arr, (elements + 1) * sizeof(char))) == NULL)
    {
        /* failed to resize array */
    }else{
        ++elements;
        arr[10] = 'v';  /* some value */    
    }
    
    /* free the array */
    free(arr);
    arr = NULL;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 11-26-2008, 10:25 AM
  2. Replies: 2
    Last Post: 11-19-2008, 02:36 PM
  3. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  4. accessing array of structs values
    By WaterNut in forum C++ Programming
    Replies: 12
    Last Post: 07-08-2004, 08:47 PM
  5. Duplicate values in Array
    By TONYMX3 in forum C++ Programming
    Replies: 2
    Last Post: 01-30-2002, 03:57 PM