121 Week 6 - Memory and Pointers Flashcards
Byte accessible memory
Each item in memory is the size of a byte and has a unique address which it can be identified by.
Words
A set number of items in memory which are grouped together.
Word size can differ between machines but are often 32 bit (4 bytes) or 64 bit (8 bytes).
Addresses for words will go up in multiples of the bytes size - 4 byte word addresses would go up by 4 each time.
Big endian format
The byte with the lowest address stores the most significant byte.
Little endian format
The byte with the lowest address stores the leastsignificant byte.
Aspects of a variable
A name, a value which it contains and an address for where the variable is stored in memory.
Pointer
A variable that holds a memory address.
Can be thought of as pointing to that location in memory
Declaring a pointer
Pointers are declared by stating the data type of the pointer, then a * to indicate it is a pointer then the name of the pointer then its value.
E.g.,
int x = 3;
int *pX = &x;
will store the address of the character variable x. The & means get address of.
Dereferencing
Dereferencing lets you get the value of what is being pointed to rather than just its address. It is done by having a * before the pointer name.
e.g.,
int x = 3;
int *pX = &x;
printf(ā%dā, *pX);
will output 3, not the address of x.
Record
A compound item that can store multiple components called fields which can be of different data types to each other.
Each field is identified using a name rather than an index.
Records hold multiple properties of a single item.
Records in C
Records in C can be defined using structs
e.g.,
typedef struct person {
char name[20];
int age;
} Person
Allocating space for records
Allocating space can be done using malloc() which takes a size in bytes as an argument then allocates this amount of memory in the heap and returns a pointer to its address.
e.g.,
Person* pt = malloc (sizeof (Student) )
sizeof() returns the size in bytes of an item.
Accessing fields
Fields of an array can be accessing using the . or -> operators
Fields from a record can be accessed using recordName.fieldName
Fields from a record stored as a pointer to it can be accessed using recordName->fieldName