Lecture 4 Flashcards
Pointers
datatype* name;
pointer initialization, “*” after data type –> creates a pointer
&name
&: returns the memory address of where the variable is stored
int i = 10;
int* p = &i;
what is p assigned to?
int pointer, p, holds the address location of another variable (int i) stored in memory
int i = 10;
int* p = &i;
printf(“%p\n”, p);
:
:
i –> memory address is 1056.
what does this print?
prints the address in main memory that this pointers, p, pointing to
prints 1056 –> int i memory address that pointer p points to
%p
format specifier that expects pointers
pointer on 64-bit system
= 8 bytes
int on 64-bit system
= 4 bytes
how many address locations do you need for an int on a 64-bit system?
4 address locations
pointer dereferencer
*NameOfPointer
what does *nameOfPointer do?
- : dereferences the pointer from the memory address of the variable, and sets it to the value stored at that memory address
int i = 10;
int * p = &i;
printf(“%d\n”, *p);
:
:
Main Mem Addy
i 10 1056
:
p 1056 2000
what does this print?
dereferences pointer p @ 1056 (memory address of int i), and prints the value stored there instead
prints 10
int i = 10;
int* p = &i;
*p = 20;
printf(“%d\n”, *p);
:
:
Main Mem Addy
i 20 1056
:
p 1056 2000
what does this print?
dereferences the pointer p @ 1056 and changes the value to 20 at that same memory address (*p = 20)
prints 20 (int i = 20 now)
int i = 10;
int* p = &i;
what line of code do we need if we want to print the value p points to?
printf(“%d\n”, *p);
int i = 10;
int* p = &i;
int* q = p;
printf(“%d\n”, *q);
:
:
Main Mem Addy
i 10 1056
:
p 1056 2000
q 1056 2008
what does this “int* q = p;” mean?
int pointer q points to pointer p which points to the memory address of int i. q points to the memory address of i since p points there and q points to p.
int i = 10;
int* p = &i;
int* q = p;
printf(“%d\n”, *q);
:
:
Main Mem Addy
i 10 1056
:
p 1056 2000
q 1056 2008
what does gets printed?
prints 10
q points @ p
p points @ 1056
q points @ 1056
dereferenced q (*q) –> prints 10 because that’s the value stored at that memory address (1056)