Resize a Statically Allocated Array

This is a discussion on Resize a Statically Allocated Array within the C Programming forums, part of the General Programming Boards category; i get 20 in both outputs, y has the array not grown ? Code: #include <stdio.h> #include <stdlib.h> int main( ...

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    99

    Resize a Statically Allocated Array

    i get 20 in both outputs, y has the array not grown ?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main( void )
    {
        int bytes[5];
        int * pBytes = bytes;
    
        printf("%d",sizeof(bytes));
    
        pBytes = (int*)realloc( pBytes, 2 * sizeof( bytes ) ); // grow it 2x
    
        printf("%d",sizeof(bytes));
        
        getchar();
        return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2006
    Posts
    903
    What you did is allocate memory for pBytes. I don't know if this is ever guaranteed to work, as you used realloc() and pBytes had no memory allocated for it. I don't think you can change the size of a statically-allocated variable.

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,340
    > pBytes = (int*)realloc( pBytes
    You can't resize an array.
    The only thing you can pass to realloc is the result of a previous malloc / calloc / realloc call.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Registered User
    Join Date
    Jun 2007
    Posts
    99
    thanx!

    so statically allocated arrays cannot be resized!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 08:51 AM
  3. Run-time error with dynamically allocated 3-D array
    By OceanDesigner in forum C Programming
    Replies: 2
    Last Post: 10-21-2005, 02:29 PM
  4. two dimensional dynamic array?
    By ichijoji in forum C++ Programming
    Replies: 6
    Last Post: 04-14-2003, 04:27 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM

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