Understanding Pointers in C Programming
Understanding Pointers in C Programming
bd/cse/users/faculty/reazahmed/
[Link]
CSE 105
Structured Programming Language
(C)
Presentation - 5
3
CSE, BUET CSE-105 – Structured Programming
pointer
Referencing & Dereferencing &
variable
* []
Reference/ Dereference/
Declaration Pointer/ Variable/
Address/LValue Content/RValue
int x; &x x
z z[0]
int z[10], i; z+i *(z+i)
&z[i] z[i]
ptr *ptr or ptr[0]
int *ptr, i; ptr+i *(ptr+i)
&ptr[i] ptr[i]
6
CSE, BUET CSE-105 – Structured Programming
Storage of Values in Memory
Same memory location can be interpreted
in different ways:long int
Intrepreted as
1 long int
41 43 45 47 0x41434547
short int
7832 47
Intrepreted as
45 47 0x4547
7833 45
2 short int
7834 43 41 43 0x4143
7835 41
char
47 ‘G’
4-bytes in RAM Intrepreted as
4 char 45 ‘E’ Note: All numbers
in this slide are in
43 ‘C’
Higher bits hexadecimal
41 ‘A’ system.
stored in higher 7
CSE, BUET address CSE-105 – Structured Programming
Pointer Operations (K R- p103 last para) n
AllOperation
other pointer arithmetic
Type of
are illegal.
Comment
result
pi Pointer pointer int pointer
a:
a[0] a[1] a[2] a[3] a[4] a[5]
*cp: E
cp:8996 78 38
*(cp+1): A
i:7838 45
7839 41 Logical View
hi-8bits [7839]
ip:8976 78 38 *ip: 41 45
RAM bytes lo-8bits [7838]
11
CSE, BUET CSE-105 – Structured Programming
2-- Assignment of Pointers
Cast and then assign
long int l = 0x41434547, *lp = &l;
int *ip = (int *)lp; // same as int *ip = (int *)&l;
char *cp = (char *)lp; // same as char *ip = (char *)&l;
lp:8974 78 32 Note:
l:7832 47
lp, ip and cp are all of
ip:8976 78 32
size 2 bytes though they
7833 45 cp:8978 78 32 are pointing to data of
7834 43 different sizes, 4, 2 and
1 bytes, respectively.
7835 41
RAM bytes
12
CSE, BUET CSE-105 – Structured Programming
2-- Assignment of Pointers
Cast and then assign
long int l = 0x41434547, *lp = &l;
int *ip = (int *)lp;
char *cp = (char *)lp;
printf(“%c %c %c %c %x %x %lx”,
*cp, *(cp+1), *(cp+2), *(cp+3), *ip, *(ip+1),
*lp);
14
CSE, BUET CSE-105 – Structured Programming
3– Comparing/Subtraction to Pointer
The resulting type of subtracting two pointers is
integer.
Comparison Vs. Subtraction
a<ba–b<0
a == b a – b == 0
a>ba–b>0
Compared/Subtracted pointers should point in same
array.
Example:
}
return p – s;
pointer - pointer int
15
CSE, BUET CSE-105 – Structured Programming
4– Comparing/Assigning to Zero
Zero is the only integer that can be
assigned to a pointer
Zero is the only integer that a pointer can
be compared to.
Use this to initialize a pointer and to
check validity
char *m = 0;
...
if (m != 0) { ... safe to use the pointer ... }
NULL can be used instead of 0
16
CSE, BUET CSE-105 – Structured Programming
Be Careful with * and ++/--
* and ++ / -- are executed from right to
left
char *p = “XAD”;
char *q = p;
Statemen
char c; c p q Comment
t
c = ++*q; ‘Y’ “YAD” p Increment content of q and return
new value.
c = *++q; ‘A’ “XAD” p+1 Increment q and fetch content.
c = *q++; ‘X’ “XAD” p+1 fetch content of q and then
increment q. i.e., c=*q; q++;
c = (*q)+ ‘X’ “YAD” p Return content of q and then
+; increment content of q. i.e. c=*q;
(*q)++;
The above is also true for the – – operator.
17
CSE, BUET CSE-105 – Structured Programming
Pointer Vs Array
char amessage[] = “now is the time”; // an array
amessage: now is the time\0
19
CSE, BUET CSE-105 – Structured Programming
Pointer Vs Array
In function argument array and pointer are same. i.e.,
following declaration/definition of function are equivalent
int strlen(char *str)
int strlen(char str[ ])
Arguments are passed by value, thus only a copy is
passed.
/* strcpy: copy t to s */
void strcpy(char *s, char *t) s: 4397
{ t: 9643
while (*s++ = *t++)
;
} 4397
……… p:
char p[25];
char *q = “Hello world”; q: Hello world\0
strcpy(p, q); 9643
What is the effect of writing
20
CSE, BUET
s=t?
CSE-105 – Structured Programming
strcmp example
/* strcmp: return <0 if s<t, 0 if s==t, >0 if s>t */
int strcmp(char *s, char *t)
{
int i;
for (i = 0; s[i] == t[i]; i++)
if (s[i] == ‘\0’)
return 0;
return s[i] – t[i];
}
21
CSE, BUET CSE-105 – Structured Programming
Stack: implementation of an int stack
int *buf; //memory for stack
int *sp; // stack pointer
7832 sp:9642
int stack_size; buf:
void init_stack(int size) { 7834
buf = (int *)malloc(size*sizeof(int));
7836
sp = buf;
stack_size = size; 7838
}
void push(int value) {
if (sp – buf >= stack_size)
printf(“\nstack is full.”); RAM bytes
else
// possible usage of the stack
*sp++ = value;
int x;
} init_stack(5);
void pop(int *value) { push(10);
if (sp == buf) push(32);
printf(“\nstack is empty.”); pop(&x); // returns 32
else // use x
… … …
*value=*--sp;
// if stack is no longer needed
}
free(buf); 22
CSE, BUET CSE-105 – Structured Programming
DIY: Do It Yourself
Do Exercise 5-3
Do Exercise 5-4
Do Exercise 5-5
23
CSE, BUET CSE-105 – Structured Programming
Pointer Arrays (K R 5.6) n
int main(void) {
int nlines;
if ((nlines = readlines(lineptr, MAX_LINES)) >= 0) {
qsort(lineptr, 0, nlines-1);
writelines(lineptr, nlines);
}
// else handle errors. see page 108.
}
24
CSE, BUET CSE-105 – Structured Programming
Pointer Arrays (K R 5.6) n
daytab[0]
char *name[] = {
“illegal month”, “January”, “February”, “March”, “April”,
“May”, “June”, “July”, “August”, “September”, “October”,
“November”, “December” };
[2] February\0
…
…
[12] December\0
29
CSE, BUET CSE-105 – Structured Programming
Pointers Vs. Multi-dim Arrays (K R 5.9) n
int a[10][20]
a 20
a is a 2D array:
…
200 int sized locations have been set aside …
10
a[row][col] is calculated as 20row+col
…
int *b[10]
…
b is a 1D array of pointers to int. …
Only 10 pointers are allocated
b[i] must be initialized/allocated with b
code (malloc) or static initialized (like 10
name array)
int **c
c is a point of pointers to int.
Only 1 pointer is allocated
c must be initialized/allocated with code
(malloc) c
c[i] must be initialized/allocated with
code (or static initialized (like name array)
Example in next slide
30
CSE, BUET CSE-105 – Structured Programming
Pointers Vs. Multi-dim Arrays (K R 5.9) n
(*pname + sizeof(char *) i
pname = (char **)
+ j * sizeof(char)) malloc(4*sizeof(char*));
pname has LValue pname[0] = “illegal”;
Pname[1] = “Jan”;
pname++; pname=name; are valid
pname[2] = “Feb”;
31
CSE-105 – Structured Programming pname[3] = “Mar”;
CSE, BUET
Comman-line Arguments (K R 5.10) n
int i;
for (i = 1; i < argc; i++)
printf(i>1? “ %s” : “%s”,
argv[i]);
return 0;
} 32
CSE, BUET CSE-105 – Structured Programming
Comman-line Arguments (K R 5.10) n
++argv (*++argv)[0]
(*++argv)
- x f r \0
0 -m\0
34
CSE, BUET CSE-105 – Structured Programming
Comman-line Arguments (K R 5.10) n
0 *++argv[0]
-m\0
35
CSE, BUET CSE-105 – Structured Programming
Complicated Declarations (K R 5.12) n
36
CSE, BUET CSE-105 – Structured Programming
Complicated Declarations (K R 5.12) n
char (*(*x())[5])()
char ( * ( * x () ) [5] ) ()
x is afunction
returning
pointer to
array[5] of
pointer to
function
returningchar
char (*(*x[3])())[5]
38
CSE, BUET CSE-105 – Structured Programming
Quick Sort : Divide and Conquer
Divide: Partition array into 2 subarrays
such that
Elements in lower part elements in
higher part
Conquer: recursively sort 2 subarrays
x x >x
39
CSE, BUET CSE-105 – Structured Programming
i l, j r
Partitioning Process 2
l, i j
8 7 1 3 5 6 4
r
Partition(A, l, r )
2 8 7 1 3 5 6 4
1. x A[ r ] l, i j r
2. i l 1 2 8 7 1 3 5 6 4
3. for j l to r 1 do l, i j r
4. if A[ j] x then 2 8 7 1 3 5 6 4
5. ii+1 l i j r
6. exchange A[ i ] 2 1 7 8 3 5 6 4
A[ j ] l i j r
2 1 3 8 7 5 6 4
7. exchange A[ i+1 ] A[ r
l i j r
]
2 1 3 8 7 5 6 4
8. return i + 1
l i r
l i j r 2 1 3 8 7 5 6 4
x >x ? x l i r
40
CSE, BUET CSE-105 – Structured Programming
2 1 3 4 7 5 6 8
Quick Sort : Algorithm
QuickSort(A, l, r )
1. if l < r then
2. q Partition(A, l, r )
3. QuickSort(A, l, q 1 )
4. QuickSort(A, q + 1, r )
41
CSE, BUET CSE-105 – Structured Programming
Pointer Arrays (K R 5.6) n
x A[ r ]
Partition(A, l, r )
il1
void qsort(char *A[], int l, int r) { for j l to r 1 do
int i, j, q; if A[ j] x
char *x; then
void swap(char **pa, char **pb); ii+1
if (l < r) {
A[ i ] A[ j ]
A[ i+1 ] A[ r ]
for ( x = A[r], i = l-1, j = l; j <= r-1; j++)
return i + 1
if (strcmp( A[j], x) <= 0)
q=partition(A, l, r);
swap( &A[++i], &A[j]);
swap( &A[i+1], &A[r]);
q = i+1; QuickSort(A, l, r )
qsort( A, l, q-1); if l < r then
qsort( A, q+1, r); q Partition(A,
} l, r )
} QuickSort(A, l, q
1)
void swap(char **pa, char **pb) {
char *temp; QuickSort(A, q +
temp = *pa; 1, r )
*pa = *pb; v[i]:7744 defghi\0
*pb = temp;
jklmnopqrst\0
} pa 7744
v[j]:7748 abc\0
pb 7748
42
CSE, BUET CSE-105 – Structured Programming
Pointer Arrays (K R 5.6) n
43
CSE, BUET CSE-105 – Structured Programming
Pointers to Functions (K R 5.11) n
swap(&A[i+1], &A[r]);
q = i+1;
qsort(A, comp, l, q-1);
qsort(A, comp, q+1, r);
}
}
int comp_int(void *x, void *y) {
void swap(void **pa, void **pb){
return *(int *)x - *(int *)y;
void *temp;
temp = *pa; }
*pa = *pb; int comp_str(void *a, void *b) {
*pb = temp; return strcmp((char *)a, (char *)b);
} } 44
CSE, BUET CSE-105 – Structured Programming
Pointers to Functions (K R 5.11) n
45
CSE, BUET CSE-105 – Structured Programming
Pointers to Functions (K R 5.11) n
46
CSE, BUET CSE-105 – Structured Programming