pure C structure

definition

1
2
3
4
5
typedef struct gid_ {
double x;
double y;
char* name ;
} gid ;

typedef defines “gid” as an alias name to “struct gid_ “. typedef also alias function handle/pointer, which is often used in asynchronous/event callback programming. other data encapsulation are:
enum : map a list of const names to integral constants
union: store many data type in one memory address

initialization

1
2
3
gid g1={2.0, 3.0, "g1"};
gid g2={.x=2.0, .y=3.0, .name="g2"};
gid g3=(gid){2.0, 3.0, "g3"};

in C++, structure initialization can also be done in constructor.

memory alignment

for better memory access in CPU architecture, memory alignment in structure is considered. namely:

chars can start on any byte address
2-bytes shorts must start on an even address 
4-bytes ints/floats must start on an address divisible by 4
8-bytes doubles/longs must start on an address divisible by 8 

the size of the whole structure, is aligned to intergeral times of the max size of its member variable. e.g. sizeof(gid) = 24, not 8+8+4.

to put the member variables in ascending/descending order is good practice.

structure pointer arithmetic

“gid++” will step forward the sizeof(gid); structure also supports self-reference:

1
2
3
4
5
6
typedef struct gid_ {
char *name ;
double x;
double y;
gid_ *next_gid ;
} gid ;

another common utils is structure array:

1
2
gid gid_list[MAX_SIZE];
gid **gid_list_p ;

structure as function parameters

in general, structure can be passing to function by value or by pointer, but not by reference in pure C. also structure as return value from function can be value or a pointer

structure in C++

in C++, structure supports member functions, is same as a public class. and the initialization can be done either in constructor function or direct initialization during definition. see the difference of struct between C and C++

stdlib.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* convert string s1 to an int*/
int atoi(const char* s1);
/* memory op */
void* malloc(size_t size);
void free(void *ptr);
/* system level op */
char* getenv(const char *name);
int system(const char *command);
/* algorithms */
void* bsearch(const void* key, const void* base,
size_t nitems, size_t size, int(*compar)(const void*, const void*))
void qsort(void *base, size_t nitems, size_t size,
int(*compar)(const void*, const void*))