COM S 326X Deep C Programming for the 21st Century Prof. Rozier Unit 4 – Variables, Continued
Arrays Related data stored under a single variable name with an index.
Arrays What are they really? Constant pointers
Strings No default string type in C. C strings are just character arrays. Null terminated. Library <string.h> contains useful constructs.
Other memory patterns We can also have patterns of data with different types. structs – a data “structure” containing potentially different types of data as “members” accessed by the “.” operator, or the member “->” operator. unions – like a struct, but the members occupy the same space in memory.
Structures
Struct/Union Example Member access: For “constant” structs and unions: name.member For pointers to structs and unions: name->member OR (*name).member
Struct/Union example GDB of struct-union-demo.c
A tale of *, ., and -> The original C Reference Manual (CRM) described a very different language from C. In CRM, a structure’s member defined a byte offset across all structs, so S and X could co-exist: but Y would cause an error:
A tale of *, ., and -> Historically this made -> a requirement, but today: a->b is just a synonym for (*a).b Still useful! *, ., and -> are all operators and as such have precedence rules in the compiler. The ‘.’ operator has higher precedence than ‘*’. So: a->b->c->d needs to be written: (*(*(*a).b).c).d
Bit fields Sometimes we want to build simple indicator variables or control allocation in structures.
Uses of unions In some embedded contexts, they help save memory usage. Can also be used for individual addressing of bitfields or composite types. union-packet.c
Unions for memory efficiency and mutable types
Typedef C lets us use the “typedef” keyword to create new names for data types.
Enumeration constants The enum keyword declares an enumeration constant.
return_type (*functionptr)(arg types); Function Pointers We can also have variables which point to functions. Declare as follows: return_type (*functionptr)(arg types);
Function Pointers - typedef
Dynamic Memory malloc, calloc, realloc, free
Dynamic Memory malloc, calloc, realloc, free
Dynamic Memory: Error Handling malloc, calloc, realloc, free
Dynamic Memory malloc, calloc, realloc, free Free is neither recursive, nor intelligent!
Building Abstract Data Types