Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Populate and process arrays of structs in C, with error handling.
- *
- * Zero-Clause BSD (0BSD)
- * ---------------------------------------------------------------------
- * Permission to use, copy, modify, and/or distribute this software for
- * any purpose with or without fee is hereby granted.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
- * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
- * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
- * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
- * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- * ---------------------------------------------------------------------
- */
- #ifndef _POSIX_C_SOURCE
- #define _POSIX_C_SOURCE 200809L
- #endif
- #include <errno.h>
- #include <stdint.h>
- #include <stdio.h>
- #include <stdlib.h>
- struct tag {
- uint32_t id;
- char *value;
- };
- void populate(struct tag **, size_t *);
- void process(struct tag *, size_t);
- void
- populate(struct tag **tags, size_t *ntags)
- {
- if (tags == NULL || ntags == NULL) {
- errno = EINVAL;
- return;
- }
- *tags = calloc(3, sizeof(struct tag));
- if (*tags == NULL)
- return;
- *ntags = 3;
- (*tags)[0] = (struct tag){79, "spam"};
- (*tags)[1] = (struct tag){97, "eggs"};
- (*tags)[2] = (struct tag){101, "crap"};
- }
- void
- process(struct tag *tags, size_t ntags)
- {
- size_t n;
- if (tags == NULL || ntags <= 0) {
- errno = EINVAL;
- return;
- }
- for (n = 0; n < ntags; ++n) {
- struct tag *t = &tags[n];
- if (t != NULL)
- printf("%3d %s\n", t->id, t->value);
- }
- }
- int
- main(void)
- {
- struct tag *tags = NULL;
- size_t ntags;
- populate(&tags, &ntags);
- process(tags, ntags);
- free(tags);
- return 0;
- }
Add Comment
Please, Sign In to add comment