Data Structures Notes
Data Structures Notes
-Variables are stored in one of three places depending on their type. The Stack
segment, Data segment or Heap.
-Local/Automatic variables are stored in the Stack segment
-Global/Static variables are stored in the Data segment (Even ones that are
created inside a function)
-Dynamic variables are stored in the Heap
In C# and Java, arrays are basically objects of a class and they are stored in the
Heap. Any variable where we use the new keyword gets stored in the Heap,
whether that’s a single variable or an array.
First, we declare a pointer int* p. This variable will be stored in the Stack
Segment:
Then, we define the variable by writing
p = (int *) malloc(sizeof(datatype). What this will do
is allocate the specified amount of memory in the
Heap and the memory address will be stored in p.
So, the variable itself is in the Stack Segment and it
Holds the address of the memory which is allocated in
The Heap
Declaration: int* p
Definition: p = (int *) malloc(sizeof(datatype))
Initialization = *p = 15
The malloc function returns a void pointer (*void) and takes an unsigned(+ve)
integer as its input. A void pointer is a pointer that can hold the address of any
variable type. That’s why we have to type case the return value by writing
(datatype *) else it will give an error.
Note: A pointer that has not been initialized is called a dangling pointer and
points to a random memory location. Using it before initialization will crash the
program
The difference between using this method and simply writing int data[4] is that
the above method creates a dynamic array in the Heap while int data[4] creates
a static array in the Stack segment.
The job of the garbage collector is to scan the memory and check to see if there
is any allocated memory in the Heap that can’t be accessed through a variable in
the Stack or Data Segment. If it finds any allocated memory that cant be
accessed it will free it.
In C# and Java this is done automatically but in C/C++ we have to do it manually
using the delete(only C++) keyword or the free function
It is necessary to specify the size of a static array before runtime however for
dynamic arrays we can do it at runtime too
To create a jagged array, we will need to take the colCount as an input in each
iteration of the loop