CS137 Lecture Notes - Lecture 16: C Dynamic Memory Allocation, C Syntax
Document Summary
// end with break; statement statement case constant. expression: case constant. expression: default: statements. Void *realloc (void *p, size _t size): reallocates previously allocated block of memory (usually to make bigger, pointer may change, can grow by appending storage or allocating new storage and copying contents. // repackage malloc and realloc to check for failure. Safe. h void *safemalloc (size_t size); void *saferealloc (void *p, size_t size); #include void *safemalloc (size_t size) void *p = malloc(size); assert (p); return (p); Pointers to structs example struct tod {int hour, minute;}; struct tod *t = (struct tod *) malloc (sizeof(struct tod)); // accessing members are (*t). hour = 18; or t->hour = 18. #include struct vector *vectorcreate() { struct vector *v = (struct vector*) safemalloc (sizeof(struct vector)); v -> size = 1; v -> length = 0; v -> a = (int*)safemalloc(sizeof(int)); return v; struct vector *vectordelete (struct vector *v) {