Last active
October 19, 2020 06:46
-
-
Save FedeDP/436a99330b2379f0c56ceedbbf02b122 to your computer and use it in GitHub Desktop.
Iterate through struct members, taken from http://stackoverflow.com/questions/1784782/is-there-any-way-to-loop-through-a-struct-with-elements-of-different-types-in-c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <time.h> | |
#include <stdlib.h> | |
#define X_FIELDS \ | |
X(char *, field1) \ | |
X(char *, field2) \ | |
X(char *, field3) \ | |
X(char *, field4) \ | |
X(char *, field5) | |
typedef struct { | |
#define X(type, name) type name; | |
X_FIELDS | |
#undef X | |
} mystruct; | |
void iterate(mystruct *a) { | |
#define X(type, name) \ | |
printf("mystruct.%s = %s\n", #name, a->name); | |
X_FIELDS | |
#undef X | |
} | |
int main(int argc, char *argv[]) { | |
char year[5] = {0}; | |
time_t t = time(NULL); | |
struct tm *tm = localtime(&t); | |
int y = tm->tm_year + 1900; | |
snprintf(year, sizeof(year), "%d", y); | |
mystruct a = { year, "year", "of", "linux", "desktop"}; | |
iterate(&a); | |
y++; | |
snprintf(year, sizeof(year), "%d", y); | |
a.field1 = strdup(year); | |
printf("\nFixed it!\n\n"); | |
iterate(&a); | |
free(a.field1); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
гавно код ебанный