Skip to content

Instantly share code, notes, and snippets.

@mzipay
Created January 18, 2019 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzipay/2fd02d3e3e2e62ed7b7e2ff56ee9834f to your computer and use it in GitHub Desktop.
Save mzipay/2fd02d3e3e2e62ed7b7e2ff56ee9834f to your computer and use it in GitHub Desktop.
C arrays of structs
/*
* 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment