4. Structs, Unions, Data Sizes
14/02/23
Structs
- structs and classes are virtually the same thing in C++
- Use
struct
to create a new structure. and.
to access values of it - Once defined can use as any other type
- Can take the address of a variable of type
struct
and store it in astruct
pointer - Can embed a
struct
as a member of anotherstruct
- Can create an array of
structs
sizeof()
is total of the size of the members
Either pass the struct into a function or a pointer
Allocating memory from the heap
malloc()
will allocate bytes of memory- Will not (directly) allocate a string for you, or an array, or an int
- In C++ you have constructors, and may add hidden things to your objects
- Should store the returned address in a pointer of the type you wish to use it as
malloc()
returns avoid*
Steps to dynamic memory bliss
- Work out how much memory you need to allocate
- Ask for that amount of memory
- Store the returned pointer
- Use the memory through the pointer, as if it was the correct type
- When finished, free the memory
Positioning of struct elements
- Like arrays, the positions of the members inside a
struct
are known - Elements will be placed sequentially in memory, in the order they are defined in the structure
#pragma
structs
may get empty space in them- Can usually tell compiler to pack structs, ignoring speed
#pragma
means a compiler/os specific pre-processor directive
Unions
- Very similar to
structs
except that the data members are in the same place - In
union
s data members all have the same address - Elements of unions are in the SAME place and may be different sizes
- Unions is as big as the biggest thing inside of it
sizeof()
is of the largest member
Bit fields
- Within structs you can specify fields with size less than a byte
C++ Things
- C++ structs can also act as full classes
- Structs default to public, whereas classes are private
Use new
to create a new object of type
New
- Knows how big the object is
- Creates an object and returns a pointer
- How to create the object in memory
- Calls the constructor
- Throws an exception if it fails
delete
- destroys an object
Both have a []
version for creating and destroy arrays