Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- /** realloc 'ptr' of 'nelem' of 'psz' to 'nelem * 2' of 'psz'.
- * returns pointer to reallocated block of memory with new
- * memory initialized to 0/NULL. return must be assigned to
- * original pointer in caller.
- */
- void *xrealloc2 (void *ptr, size_t psz, size_t *nelem)
- { void *memptr = realloc ((char *)ptr, *nelem * 2 * psz);
- if (!memptr) {
- perror ("realloc(): virtual memory exhausted.");
- exit (EXIT_FAILURE);
- } /* zero new memory (optional) */
- memset ((char *)memptr + *nelem * psz, 0, *nelem * psz);
- *nelem *= 2;
- return memptr;
- }
- char **copy_sentinel_array (char **list)
- {
- char **buffer = NULL;
- size_t avail = 2, used = 0;
- /* allocate/validate 2 pointers initially */
- if (!(buffer = calloc (avail, sizeof *buffer))) {
- perror ("calloc-buffer");
- exit (EXIT_FAILURE);
- }
- while (*list) { /* for each word in list */
- size_t len = strlen (*list); /* get length */
- if (!(buffer[used] = malloc (len + 1))) { /* allocate storage */
- perror ("malloc-buffer[used]");
- exit (EXIT_FAILURE);
- }
- memcpy (buffer[used], *list, len + 1); /* copy list->buffer */
- if (++used == avail) /* is realloc req'd? (save room for NULL) */
- buffer = xrealloc2 (buffer, sizeof *buffer, &avail);
- list++; /* increment list */
- }
- buffer[used] = NULL; /* set sentinel NULL */
- return buffer; /* return buffer */
- }
- int main (void) {
- char *list[] = { "My", "Dog", "Has", "Fleas", "My", "Cat",
- "Has", "None", "--", "Lucky", "Cat", NULL };
- char **buf = copy_sentinel_array (list); /* copy list->buf */
- size_t n = 0;
- while (buf[n]) {
- printf (" %s", buf[n]);
- free (buf[n++]);
- }
- free (buf);
- putchar ('\n');
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement