Guest User

Untitled

a guest
Jan 19th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. /*
  2. * Populate and process arrays of structs in C, with error handling.
  3. *
  4. * Zero-Clause BSD (0BSD)
  5. * ---------------------------------------------------------------------
  6. * Permission to use, copy, modify, and/or distribute this software for
  7. * any purpose with or without fee is hereby granted.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
  10. * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
  11. * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
  12. * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  13. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  14. * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  16. * PERFORMANCE OF THIS SOFTWARE.
  17. * ---------------------------------------------------------------------
  18. */
  19.  
  20. #ifndef _POSIX_C_SOURCE
  21. #define _POSIX_C_SOURCE 200809L
  22. #endif
  23.  
  24. #include <errno.h>
  25. #include <stdint.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28.  
  29. struct tag {
  30. uint32_t id;
  31. char *value;
  32. };
  33.  
  34. void populate(struct tag **, size_t *);
  35.  
  36. void process(struct tag *, size_t);
  37.  
  38. void
  39. populate(struct tag **tags, size_t *ntags)
  40. {
  41. if (tags == NULL || ntags == NULL) {
  42. errno = EINVAL;
  43. return;
  44. }
  45.  
  46. *tags = calloc(3, sizeof(struct tag));
  47. if (*tags == NULL)
  48. return;
  49.  
  50. *ntags = 3;
  51. (*tags)[0] = (struct tag){79, "spam"};
  52. (*tags)[1] = (struct tag){97, "eggs"};
  53. (*tags)[2] = (struct tag){101, "crap"};
  54. }
  55.  
  56. void
  57. process(struct tag *tags, size_t ntags)
  58. {
  59. size_t n;
  60.  
  61. if (tags == NULL || ntags <= 0) {
  62. errno = EINVAL;
  63. return;
  64. }
  65.  
  66. for (n = 0; n < ntags; ++n) {
  67. struct tag *t = &tags[n];
  68. if (t != NULL)
  69. printf("%3d %s\n", t->id, t->value);
  70. }
  71. }
  72.  
  73. int
  74. main(void)
  75. {
  76. struct tag *tags = NULL;
  77. size_t ntags;
  78.  
  79. populate(&tags, &ntags);
  80. process(tags, ntags);
  81.  
  82. free(tags);
  83.  
  84. return 0;
  85. }
Add Comment
Please, Sign In to add comment