Advertisement
drankinatty

C - Copy List w/Sentinel NULL

Oct 4th, 2019
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.02 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. /** realloc 'ptr' of 'nelem' of 'psz' to 'nelem * 2' of 'psz'.
  6.  *  returns pointer to reallocated block of memory with new
  7.  *  memory initialized to 0/NULL. return must be assigned to
  8.  *  original pointer in caller.
  9.  */
  10. void *xrealloc2 (void *ptr, size_t psz, size_t *nelem)
  11. {   void *memptr = realloc ((char *)ptr, *nelem * 2 * psz);
  12.     if (!memptr) {
  13.         perror ("realloc(): virtual memory exhausted.");
  14.         exit (EXIT_FAILURE);
  15.     }   /* zero new memory (optional) */
  16.     memset ((char *)memptr + *nelem * psz, 0, *nelem * psz);
  17.     *nelem *= 2;
  18.     return memptr;
  19. }
  20.  
  21. char **copy_sentinel_array (char **list)
  22. {
  23.     char **buffer = NULL;
  24.     size_t avail = 2, used = 0;
  25.    
  26.     /* allocate/validate 2 pointers initially */
  27.     if (!(buffer = calloc (avail, sizeof *buffer))) {
  28.         perror ("calloc-buffer");
  29.         exit (EXIT_FAILURE);
  30.     }
  31.    
  32.     while (*list) {                                 /* for each word in list */
  33.         size_t len = strlen (*list);                /* get length */
  34.         if (!(buffer[used] = malloc (len + 1))) {   /* allocate storage */
  35.             perror ("malloc-buffer[used]");
  36.             exit (EXIT_FAILURE);
  37.         }
  38.         memcpy (buffer[used], *list, len + 1);      /* copy list->buffer */
  39.         if (++used == avail)    /* is realloc req'd? (save room for NULL) */
  40.             buffer = xrealloc2 (buffer, sizeof *buffer, &avail);
  41.         list++;             /* increment list */
  42.     }
  43.     buffer[used] = NULL;    /* set sentinel NULL */
  44.    
  45.     return buffer;          /* return buffer */
  46. }
  47.  
  48. int main (void) {
  49.    
  50.     char *list[] =  { "My", "Dog", "Has", "Fleas", "My", "Cat",
  51.                         "Has", "None", "--", "Lucky", "Cat", NULL };
  52.     char **buf = copy_sentinel_array (list);    /* copy list->buf */
  53.     size_t n = 0;
  54.    
  55.     while (buf[n]) {
  56.         printf (" %s", buf[n]);
  57.         free (buf[n++]);
  58.     }
  59.     free (buf);
  60.     putchar ('\n');
  61.    
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement