Download presentation
Presentation is loading. Please wait.
Published byPhilomena Cross Modified over 9 years ago
1
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011
2
Static Arrays If the size of the array is known and will not change, then it can be initialized with the array. int array[10]; This is an array of integers with space for 10 objects.
3
Dynamic Arrays If you don't know the size of an array in the beginning, or if the size changes, then the array is dynamic. Some methods that change memory allocation are: malloc- allocates a memory block calloc- allocates space for an array in memory realloc- reallocates a memory block
4
Realloc void *realloc( void *ptr, size_t size ); realloc is a function which takes in two parameters: ptr is a pointer to a memory block previously allocated with malloc, calloc, or realloc (if NULL, the function creates and allocated block and returns its pointer). size is the size of the new block in bytes.
5
Example int input,n; int count=0; int * numbers = NULL; int * more_numbers; do { printf ("Enter an integer value (0 to end): "); scanf ("%d", &input); count++; more_numbers = (int*) (realloc numbers, count * sizeof(int)); if (more_numbers!=NULL) { numbers=more_numbers; numbers[count-1]=input; } else { free (numbers); puts ("Error (re)allocating memory"); exit (1); } } while (input!=0);
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.