Advertisement
drankinatty

C preserve const for array of pointer to struct

Aug 29th, 2015
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.96 KB | None | 0 0
  1. /* preserving const of pointer in array of pointer to struct */
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. struct ds {
  8.     size_t sz;
  9.     char word[10];
  10. };
  11.  
  12. void *new_ds() {
  13.     void *p = malloc (sizeof (struct ds));
  14.     if (!p) {
  15.         fprintf (stderr, "error: virtual memory exhausted.\n");
  16.         exit (EXIT_FAILURE);
  17.     }
  18.     return p;
  19. }
  20.  
  21. void prn_ds (const void *a, size_t n)
  22. {
  23.     size_t i;
  24.    
  25.     struct ds * const *b = (struct ds * const *)a;
  26.    
  27.     for (i = 0; i < n; i++)
  28.         printf (" size: %zu  word: %s\n", b[i]->sz, b[i]->word);
  29. }
  30.  
  31. int main (void) {
  32.  
  33.     struct ds *arr[2];
  34.     arr[0] = new_ds();
  35.     arr[1] = new_ds();
  36.    
  37.     strncpy (arr[0]->word, "hello", 10);
  38.     strncpy (arr[1]->word, "world", 10);
  39.    
  40.     arr[0]->sz = strlen (arr[0]->word) + 1;
  41.     arr[1]->sz = strlen (arr[1]->word) + 1;
  42.    
  43.     prn_ds (arr, 2);
  44.    
  45.     free (arr[0]);
  46.     free (arr[1]);
  47.    
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement