C Course: Pointers, Arrays, Macros
C Course: Pointers, Arrays, Macros
Data types
Basic types
Enumerated types
Type void
Derived types
Pointer
Array
Structure/union
function
Basic types
double b = 1.1;
void main(void) {
if(a == b)
int a = -1;
printf("pigs are awesome");
unsigned b = 1;
else
if (b > a)
printf("I'm a boob");
printf(boobs are awesome);
}
else
printf(Im a pig (schweine for Whitefucker));
}
Enumerated types
enum X {a, b, c};
enum X {a=2, b, c};
enum X {a, b=-1, c};
enum X {a, b, c}; sizeof(enum X); sizeof(a)
Q: How to count number of elements in
enum?
A: ?
Type void
Pointer
Pointer value is address to something
It can point to valid or invalid address
(therefore, segmentation fault or similar err)
It can point to a pointer (infinitely?)
Operator & returns (by convention)
address of operand (it can be used only
on lvalue)
Array
array of elements (similar to pointer to
array of elements)
Value is pointer to first element
sizeof is how much memory array takes
&array is pointer to an array of n elements
&array + 1? Why is this dangerous?
Where are those elements stored?
typedef struct {
uint8_t R;
uint8_t G;
uint8_t B;
uint8_t alpha;
} ColorRGBA;
typedef union {
uint32_t RGBA;
ColorRGBA channel;
} Color;
Arrays
int array[5][10];
sizeof(array);
sizeof(array[0]);
sizeof(&array);
sizeof(&array[0]);
void foo(int arr[]);
VLA
Pointers
void alloc(void** ptr, size_t sz);
void matrix_alloc(void*** ptr, size_t x, size_t y, size_t
data_size);
void matrix_alloc(void*** ptr, size_t x, size_t y, size_t
data_size) {
//allocate matrix size = x * y
}
how to use matrix_alloc function?
Pointers
void free(void* ptr);
void matrix_free(???);
void matrix_free(???) {
//free matrix size = x * y
}
how to use matrix_free function?
Macros
Preprocessor
#define, #include, #undef, #ifdef, #ifndef,
#if, #else, #elif, #endif, #error, #pragma
#define MAX_FILENAME_SZ 255
#ifdef __linux__
#ifdef __linux__
#undef MAX_FILENAME_SZ
#else
#endif
#endif
Predefined macros
Macro operators
Continuation Operator (\)
#define VOLUME(A, B, C) ((A) * \
(B) * \
(C))
Macro operators
Token pasting Operator (##)
#define str(X) str_##X
char *str_1=1, *str2=2, str_i=i;
int i = 1;
printf(%s, str(i));
Defined Operator
#if defined(TKEL_OS21)
#include tkel_os21.h|
#elif defined(TKEL_ECOS)
#include tkel_ecos.h
#error Unsupported operating system
#endif
Marko Grumic, BS, MS, MA, PhD, and ScD. OMG :),