CS137Part05 Pointers Arrays Malloc Post
CS137Part05 Pointers Arrays Malloc Post
• Turns out in C, you can swap two integers in just one line!
(x ^= y), (y ^= x), (x ^= y);
• Denote XOR using ⊕.
• Trace this with x0 and y0 the starting values:
• Step 1: x becomes x0 ⊕ y0
• Step 2: y becomes y0 ⊕ (x0 ⊕ y0 ) = x0 .
• Step 3: x becomes (x0 ⊕ y0 ) ⊕ x0 = y0 .
Example
stack
↓
↑
heap
constants
text
Stack vs Heap
From openclipart.com
Stack Heap
Stack vs Heap
Heap
Stack
• Memory set aside for
• Scratch space for a thread
dynamic allocation.
of execution.
• Typically only one heap for
• Each thread gets a stack.
an entire application.
• Elements are ordered (new
• Entries might be unordered
elements are stacked on
and chaotic.
older elements).
• Usually slower since need a
• Faster since
lookup table for each
allocating/deallocating
element (ie. more
memory is very easy.
bookkeeping).
Commands
• In the time of day example, the sizes of all the elements were
fixed.
• What happens if you say want a struct with an array whose
size is to be determined later?
• Turns out there are ways to handle this but it must be done
very carefully.
• This is valid only in C99 and beyond.
• This technique is called the “struct hack”.
Struct Hack Setup
# ifndef VECTOR_H
# define VECTOR_H
struct vector ;
struct vector * vectorCreate ( void );
struct vector * vectorDelete ( struct vector * v );
void vectorSet ( struct vector *v , int index ,
int value );
int vectorGet ( struct vector *v , int index );
int vectorLength ( struct vector * v );
# endif
Note: size is the total storage where as length is the actual used
storage.
Descriptions (should include in the header file!)