C language: dynamic list (struct, union, flexible array usage)

Subject: to demonstrate the usage of dynamic list (struct, union, flexible array usage) in C-language (C99).

Usage: compile source C-code (for example, with M$ Visual Studio or with GCC)

and run it with one option: the name of file (like <the name of program> <the name of file>).

//------- the start of the C code -------

/********************************************************************* * Author: Stepan A. Baranov (rosmir@gmail.com) * web-site: www.rosmir.org *********************************************************************/ #include <stdio.h> #include <stdlib.h> #if defined(_MSC_VER) // M$ Visual Studio #pragma warning (disable: 4996 4200) #endif #define bl_t 1 /* boolean type */ #define in_t 2 /* integer type */ #define fl_t 3 /* float type */ #define ivl1 vl1.in #define ivl2 vl2.in #define ivl3 vl3.in #define fvl1 vl1.fl #define fvl2 vl2.fl #define fvl3 vl3.fl union typeValue { int in; float fl; }; struct fldSpc { unsigned int Id; unsigned int type; union typeValue vl1; union typeValue vl2; union typeValue vl3; }; struct flxArray { unsigned int num; struct fldSpc fld[]; }; int main (int argc, const char *argv[]) { FILE *fp; struct flxArray *list; list = (struct flxArray *) malloc (sizeof (struct flxArray) + 4 * \ sizeof (struct fldSpc)); if (list == NULL) return EXIT_FAILURE; else list->num = 4; list->fld[0].Id = 12; list->fld[1].Id = 25; list->fld[0].type = in_t; list->fld[1].type = fl_t; list->fld[0].ivl1 = 56; list->fld[1].fvl1 = 9.067f; list->fld[0].ivl2 = 123; list->fld[1].fvl2 = 11.8765f; list->fld[0].ivl3 = 3; list->fld[1].fvl3 = 0.342f; if (argc != 2) return EXIT_FAILURE; fp = fopen (argv[1], "w+b"); if (fp == NULL) return EXIT_FAILURE; fseek (fp, 0, SEEK_SET); fwrite (&list->fld[0], sizeof(struct fldSpc), 1, fp); fwrite (&list->fld[1], sizeof(struct fldSpc), 1, fp); fseek (fp, 0, SEEK_SET); fread (&list->fld[2], sizeof(struct fldSpc), 1, fp); fread (&list->fld[3], sizeof(struct fldSpc), 1, fp); printf ("%d %d %d %d %d \n", list->fld[2].Id, list->fld[2].type, list->fld[2].ivl1, list->fld[2].ivl2, list->fld[2].ivl3); printf ("%d %d %f %f %f \n", list->fld[3].Id, list->fld[3].type, list->fld[3].fvl1, list->fld[3].fvl2, list->fld[3].fvl3); free (list); fclose (fp); return EXIT_SUCCESS; }

//------- the end of the C code -------

©2009 Rosmir - Stepan A. Baranov

$Id: dynamiclist.html 413 2009-01-06 21:16:05Z rosmir $