Thread: dynamically changing an array size in C

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    2

    dynamically changing an array size in C

    There was another thread on this topic that I was going to reply to but it was closed.


    This is my code:

    Code:
    #include <stdio.h>
    
    
    int main()
    {
    
    int *result;
    
    result = (int *) malloc(3);
    
    
    result[0] = 5;
    result[1] = 2;
    result[2] = 3;
    
    free(result);
    
    
        printf("%d \n", result[0]);
    
        return 0;
    }
    When using printf to display the value of result[0], it always says the value is 0, not 5. It displays result[1] and result[2] correctly as 2 and 3.

    What is wrong?

  2. #2
    Registered User
    Join Date
    Jan 2012
    Posts
    2
    nevermind, i already figured it out.

    The free(result) function was causing it.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    You are allocating 3 bytes, an int is most probably 4 bytes. So you will need: malloc( 3 * sizeof(int) );

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 01-13-2011, 09:46 PM
  2. Any way to dynamically change an array size in C?
    By MrSteve in forum C Programming
    Replies: 15
    Last Post: 07-15-2008, 08:32 PM
  3. Dynamically allocating array size
    By JFonseka in forum C Programming
    Replies: 1
    Last Post: 03-31-2008, 06:24 AM
  4. How To Declare and Dynamically Size a Global 2D Array?
    By groberts1980 in forum C Programming
    Replies: 26
    Last Post: 11-15-2006, 09:07 AM
  5. dynamically defined array size in a function
    By earth_angel in forum C Programming
    Replies: 21
    Last Post: 05-28-2005, 01:44 AM