Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* preserving const of pointer in array of pointer to struct */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct ds {
- size_t sz;
- char word[10];
- };
- void *new_ds() {
- void *p = malloc (sizeof (struct ds));
- if (!p) {
- fprintf (stderr, "error: virtual memory exhausted.\n");
- exit (EXIT_FAILURE);
- }
- return p;
- }
- void prn_ds (const void *a, size_t n)
- {
- size_t i;
- struct ds * const *b = (struct ds * const *)a;
- for (i = 0; i < n; i++)
- printf (" size: %zu word: %s\n", b[i]->sz, b[i]->word);
- }
- int main (void) {
- struct ds *arr[2];
- arr[0] = new_ds();
- arr[1] = new_ds();
- strncpy (arr[0]->word, "hello", 10);
- strncpy (arr[1]->word, "world", 10);
- arr[0]->sz = strlen (arr[0]->word) + 1;
- arr[1]->sz = strlen (arr[1]->word) + 1;
- prn_ds (arr, 2);
- free (arr[0]);
- free (arr[1]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement