Data Structures Flashcards
What does the function realloc do?
Allocates a requested amount of memory on the heap and returns an address to the start of the reserved memory.
What happens when you realloc
a variable old_ptr that is null?
Realloc will work like malloc
What happens when you realloc
a variable old_ptr that is NOT null?
If old_ptr is not null, will allocate enough memory for the new length using malloc and copy the old from old_ptr to new memory and then will free old_ptr.
How do you define a multi-dimensional array? (e.g 2d int array)
int days[2][13] = {
{0, 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31}
};
days[1][2];
What is an alternative approach of storing a multidimensional array?
Using pointer arrays.
How is memory allocated for multi-dimensional dynamic arrays?
With the use of an additional array containing pointers. Each array is not necessarily stored contiguously in memory.
What is the advantage of storing arrays in memory with one pointer?
- Simpler with memory management
- All allocated in heap memory in one go
-Each array is stored contiguously
What is the disadvantage of storing arrays in memory with one pointer?
If using big data, a large free contiguous block of memory to be free is required.
What are the advantages of storing arrays contiguously?
- When accessing consecutively, we can be efficient with memory access
- Allows for pointer arithmetic
What is a struct?
Data structure/Mechanism for packing multiple variables into a single block.
How do structs differ to objects?
Structs don’t have functions.
How can we access member variables of struct data structure?
Dot-syntax to access remember variables.
What are the advantages of struct?
- Helps keep correlated variables together
- Logical ordering and structure to data representation
- Pass multiple variables packed together as a single parameter to a function
- A struct allows you to return multiple variables from a function
- A struct can embed structs within it.
What is arrow syntax equivalent to?
- dereferencing a point, and
- accessing a member variables
at the same time.
What will the sizeof(struct x) give at compile time?
Gives the byte size of the variables.