1 / 5

Growing Arrays in C

Growing Arrays in C. By: Victoria Tielebein CS 265- Spring 2011. 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. Dynamic Arrays.

hildaf
Télécharger la présentation

Growing Arrays in C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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*) (reallocnumbers, 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);

More Related