Pointers & Arrays: CSE 105 Structured Programming Language (C) Presentation - 5
Pointers & Arrays: CSE 105 Structured Programming Language (C) Presentation - 5
php
CSE 105
Structured Programming Language (C)
Presentation - 5
3
CSE, BUET CSE-105 – Structured Programming
pointer
Referencing & Dereferencing &
variable
* []
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
43 ‘C’ this slide are in
Higher bits stored in hexadecimal system.
higher address 41 ‘A’
7
CSE, BUET CSE-105 – Structured Programming
Pointer Operations (K R- p103 last para) n
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:
lp, ip and cp are all of size 2 bytes
l:7832 47 ip:8976 78 32
though they are pointing to data
7833 45 cp:8978 78 32 of different sizes, 4, 2 and 1
7834 43 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:
16
CSE, BUET CSE-105 – Structured Programming
Be Careful with * and ++/--
* and ++ / -- are executed from right to left
char *p = “XAD”;
char *q = p;
char c;
Statement c p q Comment
c = ++*q; ‘Y’ “YAD” p Increment content of q and return new value.
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)++;
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 s=t?
20
CSE, BUET 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
int stack_size; 7832 sp:9642
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
[12]
28
CSE, BUET CSE-105 – Structured Programming
Initialization of Pointers (K R 5.8) n
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
b[i] must be initialized/allocated with code
10
(malloc) or static initialized (like 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)[0]
++argv
(*++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] ) ()
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
8
j
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. il1 2 8 7 1 3 5 6 4
3. for j l to r 1 do l, i j r
2 8 7 1 3 5 6 4
4. if A[ j] x then
5. ii+1 l i j r
2 1 7 8 3 5 6 4
6. exchange A[ i ] A[ j ]
l i j r
7. exchange A[ i+1 ] A[ r ] 2 1 3 8 7 5 6 4
8. return i + 1 l i j r
2 1 3 8 7 5 6 4
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
Partition(A, l, r )
x A[ 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 then
char *x; ii+1
void swap(char **pa, char **pb); A[ i ] A[ j ]
if (l < r) {
A[ i+1 ] A[ r ]
return i + 1
for ( x = A[r], i = l-1, j = l; j <= r-1; j++)
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 )
} QuickSort(A, q + 1,
void swap(char **pa, char **pb) { r)
char *temp;
temp = *pa;
*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