1/25
1. Variables as an abstraction 2. Arrays in C 3. Strings in C 4. Passing into and returning from functions
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
c It provides direct access to:
hardware and, importantly, virtual memory e.g. RAM
Every byte of memory on your computer
has a unique memory address
A variable
a way of storing information in your computer's memory
Rather than loading data in and out of memory, and the programmer having
to keep track as to what is stored where
programming languages introduce
an abstraction: a variable.
int h2g2 = 42; int words
give me an address in memory for an integer (typically 4
bytes), and write the value 42 to it
h2g2 later in your code, this is compiled to in words:
go to the address where this variable stores its value, and fetch it for me
Declarations
tell the compiler the
name and type of something
To define a variable:
int h2g2;
You can define and initialise:
int h2g2 = 42;
A definition
tell the compiler the name and type of something but also tells the compiler
where it is stored in memory
find the location of where this is stored in memory
using the ampersand unary operator (&variable)
&h2g2 gives?
gives us the location in memory
printf("The value %d is at %p\n", h2g2, &h2g2); will print what with location as x
The value 42 is at x
Why would we want a variables address?
In C, we can only pass by value and return by value and If your code is passing around big
chunks of data, this is inefficient
Pointer variables
are just variables that store memory addresses
use of pointers
to pass around and store memory addresses in our programs
how do you refer to a pointer and give an example with and int
by the type of the thing they point to, followed by an asterisk int *
int h2g2 = 42;
int *p = &h2g2;
printf("The value %d is at %p\n", *p, p); what is this code doing
using a pointer The value 42 is at x to print the location
what is this code doing:
int i;
int ptr_to_i = &i;
int *ptr_to_ptr_to_i = &ptr_to_i;
a pointer to a pointer
write hoe to declare an array of length 9
#define ARRAY_LENGTH 9
int an_array[ARRAY_LENGTH];
how do arrays allocate memory
Arrays allocate to consecutive
points in memory, based on the
size of the type of array
how can you cast an_array to pointer
int ptr = (int) an_array;
how is this code saying printf("value at index 2 is %d\n", *(ptr + 2));
Take my address and offset 2 int’s worth of memory ahead
What happens if I lie to the compiler about the
type of variable being pointed to by a pointer? for example using a char for an array of ints
It can point to the wrong location as chars are a different size than int
what are chars in c
a single ASCII or UTF-8 character in C
what are used instead of strings in C
contiguous blocks of chars in memory,
terminated by a null character (\0)