Beruflich Dokumente
Kultur Dokumente
CS1010 Lecture 7
Pointers
Henry Chia
hchia@comp.nus.edu.sg
School Of Computing
National University Of Singapore
Memory Addresses
Lecture Outline
Memory addresses
Pointers
Declaration and assignment
Dereference
Pointer comparison
count 1010
Pointers in functions
Pointer parameters
Address as return value
Pointers to structures
Address Operator
Pointer Declaration
Pointer Variable
Pointer Declaration
@100
Pointer Assignment
ptr = &count;
@300
?
@100
@300
@100
<int> count
@100
@400
Pointer Dereference
Consider the following statements:
int count, *ptr;
ptr = &count;
*ptr = 1020;
printf("Var at %p stores %d\n", ptr, *ptr);
ptr1 = &count;
Assign the address of variable count to
the variable ptr1.
@300
@100
@300
ptr = NULL;
// or ptr = 0;
CS1010 Lecture 7 p.15/31
ptr1 = y;
ptr1 = *ptr2;
Swapping Revisited
temp = *ptrX;
*ptrX = *ptrY;
*ptrY = temp;
temp = x;
x = y;
y = temp;
return;
return;
}
}
Swapping Revisited
int main(void)
{
int x = 5, y = 2;
swap(x,y);
temp = x;
x = y;
y = temp;
return;
}
main
x
int main(void)
{
int x = 5, y = 2;
swap(&x,&y);
return 0;
}
}
main
x
swap(&x,&y);
swap
2
temp
swap(x,y);
return 0;
ptrX
ptrY
When an address is passed to a function, draw a reference from the function parameter to the specified location.
CS1010 Lecture 7 p.18/31
swap(&x,&y);
ptrX
temp
ptrY
5
int main(void)
{
int a, b, sum, prod;
temp = ptrX;
ptrX = ptrY;
ptrY = temp;
return;
return 0;
}
Pointers to Structures
struct Point
{
double x, y;
};
int main(void)
{
struct Point pt = {1,2},
*pPtr;
pPtr = &pt;
return 0;
}
pt
@500
1.0
2.0
@600
pPtr
@500
Lecture Summary
If you are new to pointers, devise and use
memory addresses to assist in program
traces; then progress on to using arrows.
Ensure type-consistency when assigning
pointers.