Lecture 7, ECE264, Spring 2012, Prof. Lu
int * a;
a’s value is an address
At that address, stores an integer (integer pointer)
c = * a;
if it’s * a on the right hand side
it means to go to that variable’s address to retrieve value
- a = * b;
We take b’s value as address, and read value
Then we take a’s value as address, modify the value at that address
(Start on the right hand side, then work to the left hand side)
int * a = 5
This will be an error
int a = 5;
int * b = & a;
a is an integer
b is a pointer, and the value is the address of a
A pointer’s value is an address and an integer is stored at that address
If a pointer is on the left hand side of an assignment (=), it is to be modified.
If a pointer is on the right hand side of an assignment (=), it is to be read
printf(“%d\n”, * b);
Because * b is considered on the RHS, it reads the value at that address (i.e. -9).
If you use printf(“%d\n”, b); in the function that initializes as * b, then the function will print the address as a value (i.e. 103). The same applies when you use &b.
IPA1-1:
• read a maze file once to find the width and height
• allocate a one or two-dimensional array
• use fseek to reset the file pointer to the beginning
• read the file again and store the maze in the array
Today’s topic
• pointer (value is an address)
• heap memory
• malloc and free
Practice:
• Use one-dimensional array to implement two-dimensional array
• (hint: convert [row][col] to [index])
Practice:
• allocate the array without reading the file twice
• (hint: use fseek and ftell)
Heap Memory
It is random access:
You don’t need to follow the order first-in-last-out
It comes at a price: you must allocate and you must release (garbage collection like Java)
If a program does a lot for you, it tends to be slower. C is usually faster than Java
If you don’t release the memory, it’s called a memory leak (allocated, but not released)
If you have a memory leak in your program, you will have a -50% penalty. Memory leaks will cause unexpected crashes of your program. There are easy tools to check for memory leaks.
Memory Allocation
There are two ways to create a one-dimensional array.
1) You know the size; it’s a fixed size.
2) Array size unknown, increase as program continues
C does not initialize arrays; indexes start from zero
int arr[100];
int x;
If array starts at address 200, x will have an address of 300. It reserves 100 spaces for your array.