Lecture 9 Pointer
Lecture 9 Pointer
What is Pointer?
v A pointer is a variable whose value is the
address of another variable.
Understanding point:
Question Answer
&a 0002
a 1008
*a 12
&b 1008
b 12
12
Read out:
*a: pointer of a
&a: ampersand or address of a
Pointer Examples 1
Write down the output of the following program:
Output u=3
v=3
&u =F8E
&v =F8C
pu =F8E
pv =F8C
*pu = 3
*pv = 3
Pointer Examples 2
Write down the output of the following program:
#include <stdio.h>
main(){ 16 16
int u1, u2; u1 u2
int v = 3, *pv;
u1 = 2 * ( v + 5 );
3
pv = &v;
pv v
u2 = 2 * ( *pv + 5 );
Output u1 = 16 u2 =16
Pointer Examples 3
Write down the output of the following program:
#include <stdio.h>
main(){
int v = 3; 3
pv v
int *pv;
pv = &v;
printf(“\n*pv=%d v=%d”, *pv, v);
*pv = 0;
printf(“\n*pv=%d v=%d”, *pv, v);
}
Output *pv = 3
*pv = 0
v=3
v=0
Passing Pointer to Function
Function Arguments/Parameters
#include <stdio.h>
Output:
25D 25F 261 263 265 267 269 26B 26D 26F
A: 25D 12 14 10 23 14 30 27 19 25 13
0 1 2 3 4 5 6 7 8 9
Index
Example: A[0] = 12 A[3] = 23 A[7] = 19
*A = 12 *( A + 3 ) = 23 *( A + 7 ) = 19
A = 25D ( A + 3 ) = 263 ( A + 7 ) = 26B
Pointer and Array
Memory size:
Example: char 1 byte
For char pointer, char *A; int 2 bytes
float 4 bytes
char
A
For float pointer, float *A;
A +1 = A + size of char
A + 5 = A + 5 * size of char float
A
A +1 = A + size of float
A + 2 = A + 2 * size of float
For int pointer, int *A;
int
A
A +1 = A + size of int
A + 3 = A + 3 * size of int
Pointer and Array
Declaration of 1D Array:
int A[10];
A:
The value assigned to i begins at address F9C and the value assigned
to j begins at address F9E.
The value assigned to a begins at address 1130 and the value assigned to b
begins at address 1134 and the value assigned to c begins at 1138.
Memory address
25D 25F 261 263 265 267 269 26B 26D 26F
x: 25D 10 20 30 40 50 60 70 80 90 100
0 1 2 3 4 5 6 7 8 9
Index
person
0 1 2 3 4 5 6 7 8 9
ch ptr ch ptr ch ptr ch ptr ch ptr ch ptr ch ptr ch ptr ch ptr ch ptr
Ø This is useful for processing two-dimensional array parameters declared with unknown
number of rows.
Pointer and 2D Array
Declaration of 1D Array:
int A[5][2];
Memory address
25D 25F 261 263 265 267 269 26B 26D 26F
A: 25D 12 14 10 23 14 30 27 19 25 13
[0][0] [0][1] [1][0] [1][1] [2][0] [2][1] [3][0] [3][1] [4][0] [4][1]
Index
…
Pointer and function
int *func_name ( int a ); //function returns a pointer to an integer
Try Yourself…..
(1) int *(*f)( int a);
(2) int *(*p)(int (*a)[]);
(3) int *(*p)(int *a[]);
(4) char *f(char *a);