Check timetable!
Visualising memory with addresses
<type> *<name_of_variable>
^ The *
means don't request the storage to store <type>
, but requests memory to store a memory address of <type>
int *pointer
struct student *student
// declare a pointer to an integer
int *number; // operating system returns 0x17
&
&
&<variable>
int number = 2;
&number // the address of number
int number = 2;
int *pointer_to_number = &number
*
symbol again (which causes confusion)*my_int_pointer
-> will get the integer at the address locationint main(void) {
// Declare an integer
int my_age = 23;
// Declare an integer pointer
// Assign it the address of my_age
int *pointer_to_my_age = &my_age;
// Print out the address and value at the pointer
printf("Pointer is: %p value is: %d\n", pointer_to_my_age, *pointer_to_my_age)
return 0;
}
int number;
int *number_ptr;
number_ptr = number;
*number_ptr = &number;
int *int_pointer;
&my_variable;
*int_pointer;
Goals:
#include <stdio.h>
void change_value(int *x) {
*x = *x * 2;
}
int main(void) {
int x = 5;
change_value(&x);
printf("%d\n", x);
return 0;
}
In the previous example, by passing the memory address, we can change the value in place and main will point to the updated value!
void double_array_of_ints(int data[], int size) {
for (int I = 0; I < size; I++) {
data[i] = data[i] * 2;
}
int main(void) {
int data[5] = {1, 2, 3, 4, 5};
double_array_of_ints(data, 5);
//is data doubled?
}
^ does data in main contain the doubled values?