100% found this document useful (1 vote)
87 views

Pointers & Arrays: CSE 105 Structured Programming Language (C) Presentation - 5

The document provides an overview of pointers and arrays in C programming. It contains 3 key points: 1) Pointers are variables that hold memory addresses and can be used to indirectly access and modify other variables in memory. Common pointer operators include * to dereference and & to get the address of a variable. 2) Pointer arithmetic allows accessing elements of an array using pointers. Adding or subtracting an integer to a pointer accesses different elements in an array. 3) Passing pointers as arguments allows modifying variables in the caller function from within the called function, since pointers provide access to the actual memory location rather than a copy of the variable.

Uploaded by

Reaz Ahmed
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
87 views

Pointers & Arrays: CSE 105 Structured Programming Language (C) Presentation - 5

The document provides an overview of pointers and arrays in C programming. It contains 3 key points: 1) Pointers are variables that hold memory addresses and can be used to indirectly access and modify other variables in memory. Common pointer operators include * to dereference and & to get the address of a variable. 2) Pointer arithmetic allows accessing elements of an array using pointers. Adding or subtracting an integer to a pointer accesses different elements in an array. 3) Passing pointers as arguments allows modifying variables in the caller function from within the called function, since pointers provide access to the actual memory location rather than a copy of the variable.

Uploaded by

Reaz Ahmed
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 46

http://www.buet.ac.bd/cse/users/faculty/reazahmed/cse105.

php

Pointers & Arrays

CSE 105
Structured Programming Language (C)
Presentation - 5

CSE, BUET CSE-105 – Structured Programming


Pointers
What is pointer?
A variable (2 or 4 bytes long) that can hold an Address
Why pointers?
Sometimes the only way to express a computation
Usually lead to compact and efficient code
Related operators:
* : can be used in two ways
In declaration : read as pointer, e.g., int *p;
In accessing : read as content of, e.g., x = *p;
& : returns LValue (address) of a variable
Read as address of
2
CSE, BUET CSE-105 – Structured Programming
Pointer Examples
int x = 70, y = 80, z[4] = {10, 20, 30, 40 };
int *ip; // int pointer ip

ip = &x; // ip is assigned to address of x


*ip = 200; // content of ip is assigned to 200
y = *ip; // y is assigned to content of ip
ip = &z[2];
*ip = *ip + 20; // same as *ip += 20;
y = *ip+1; x : 4892 200
70
y : 4894 200
80
51
Z, Z[0] : 4896 10
Z[1] : 4898 20
Z[2] : 4900 30
50
Z[3] : 4902 40
ip : 4904 ????
4892
4900

3
CSE, BUET CSE-105 – Structured Programming
pointer
Referencing & Dereferencing &
variable
* []

Referencing ( & ): create reference (pointer) to memory location


Dereferencing (*, [ ] ): get the content of memory location
Reference/Pointer/ Dereference/Variable/
Declaration
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]

Note: x = 10;  *(&x) = 10;


4
CSE, BUET CSE-105 – Structured Programming
Pointers in Function arguments
Arguments are passed by value, thus only a copy is passed.
void swap_wrong(int x, int y)
{
int temp;
temp = x; in swap_wrong
x = y; in swap
y = temp;
x: 10
} px: 4397
y: 20
py: 9643
void swap(int *px, int *py)
{ temp:
temp:
int temp;
temp = *px;
*px = *py;
*py = temp;
}
in caller:
a:4397 10
int a = 10, b = 20; b:9643 20
swap_wrong(a, b);
printf(“a=%d, b=%d”, a, b);
swap(&a, &b);
printf(“a=%d, b=%d”, a, b);
5
CSE, BUET CSE-105 – Structured Programming
DIY: Do It Yourself
Go through function getint(int *pn) in page 97
Do Exercise 5-1
Do Exercise 5-2

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

The valid pointer operations are


1. Adding or subtracting a pointer and an integer (p  i)
2. Assignment of pointers of the same type (p = q)
3. Subtracting or comparing two pointers in same array (p - q)
4. Assigning or comparing to zero. (p = 0)

All other pointer arithmetic are illegal.


Operation Type of result Comment
pi Pointer pointer  int  pointer

p=q Pointer Pointer = pointer  pointer

p-q Integer Pointer – pointer  interger

p=0 Pointer 0 is the only exceptional integer that


can be assigned to a pointer.
8
CSE, BUET CSE-105 – Structured Programming
1– Addition/Subtraction with int (K R 5.3) n

Used for pointing to different elements in an array


int a[6], *pa, x, i;
pa = &a[2]; // same as pa = a + 2;
*pa  pa[0]  a[2]
*(pa-i)  pa[-i]  a[2-i]
*(pa+i)  pa[i]  a[2+i]

pa-2 pa-1 pa: pa+1 pa+2 pa+3

a:
a[0] a[1] a[2] a[3] a[4] a[5]

pointer  int  pointer


9
CSE, BUET CSE-105 – Structured Programming
1– Addition/Subtraction with int
Size of the pointed data-type is automatically taken care of.
If address of a pointer (say ptr) is A
then address of ptr+i is A+i*sizeof(data-type of ptr)
long *lp;
int *ip;
7832 12
char *cp; lp0x7832
7832 12 7833 34 *lp=
ip0x7832
*ip=0x3412 7834
0x78563412
7833 34 56
7832 12 7834 56 7835 78
cp7832 ip+10x7834
*cp=0x12 7835 ip[1]=0x4456
7833 34 44 7836 78
lp+10x7836
7834 56 7836 33 7837 56
ip+20x7836 lp[1]=
cp+27834 0x12345678
7835 ip[2]=0x5633 7838
44 cp[2]=0x56 7837 56 34
7839 12
10
CSE, BUET CSE-105 – Structured Programming
2-- Assignment of Pointers
Pointers of same types can be assigned.
float x = 10.5, *p = &x, *q = p;

Cast and then assign


int i = 0x4145, *ip = &i;
char *cp;
cp = (char *)ip;
printf(“%c %c %x”, *cp, *(cp+1), *ip);

*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);

7832 47 *cp=‘G’ 47 7832 47


7832
*ip
7833 45 *(cp+1) =‘E’ 45 0x4547 7833 45
7833 *lp
7834 0x41434547
7834 43 *(cp+2) =‘C’ 7834 43 43
*(ip+1)
41 41 0x4143 7835 41
7835 *(cp+3) =‘A’ 7835

RAM bytes RAM bytes RAM bytes


13
CSE, BUET CSE-105 – Structured Programming
2-- Assignment of Pointers
Pointer to void
is used to hold any type of pointer
int *ip;
void *vp;
vp = ip; // type casting is not essential

Cannot be de-referenced without type casting.


int x = *vp; // is illegal type casting is a must
int y = *((int *)vp); // is ok

Provides some degree of Polymorphism.

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<ba–b<0
a == b  a – b == 0
a>ba–b>0
Compared/Subtracted pointers should point in same array.
Example:

/* strlen: return length of string s*/


int strlen(char *s) {
char *p = s;
while (*p != ‘\0’)
p++;
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;
char c;

Statement c p q Comment
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

char *pmessage = “now is the time”; // a pointer


pmessage: now is the time\0

pmessage has LValue


pmessage is pointer and requires 2/4 bytes for itself
pmessage++ is possible
pmessage=somepointer is legal
amessage has no LValue
amessage is a name for the starting address of the array
amessage++ is illegal
amessage=somepointer is illegal
18
CSE, BUET CSE-105 – Structured Programming
strcpy example
/* strcpy: copy t to s */
void strcpy(char *s, char *t) Note: if you just write s=t then
{ only the pointer will be copied, not
int i;
i = 0;
the characters
while ((s[i] = t[i])!=‘\0’)
i++;
}

/* strcpy: copy t to s */ /* strcpy: copy t to s */


void strcpy(char *s, char *t) void strcpy(char *s, char *t)
{ {
while ((*s = *t)!=‘\0’) { while ((*s++ = *t++)!=‘\0’)
s++; ;
t++; }
}
}

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];
}

/* strcmp: return <0 if s<t, 0 if s==t, >0 if s>t */


int strcmp(char *s, char *t)
{
for ( ; *s == *t; s++, t++)
if (*s == ‘\0’)
return 0;
return *s – *t;
}

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

Sort an some lines of text! i.e., array of lines/text


[0] defghi\0 [0] defghi\0

[1] jklmnopqrst\0 SORT [1] jklmnopqrst\0


[2] abc\0 [2] abc\0

#define MAX_LINES 5000


char *lineptr[MAX_LINES]; // pointers to text lines

int readlines(char *lptr[], int maxlines);


int writelines(char *lptr[], int nlines);
void qsort(char *lptr[], int left, int right); // will see later

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

int readlines(char *lptr[], int maxlines) {


char *p;
for (int n = 0; n < maxlines; n++) {
p = (char *)malloc(100); // <stdlib.h>
if (gets(p) == NULL) {
free(p);
break;
}
lptr[n] = p;
}
return n;
}

int writelines(char *lptr[], int nlines) {


for (int i= 0; i < nlines; i++)
printf("%s\n", lptr[i]); // <stdio.h>
}
25
CSE, BUET CSE-105 – Structured Programming
Multi-dimensional Array (K R 5.7) n

Example: Date conversion problem


day_of_year
Input: year, month, day (i.e., date)
Output: day of the year. (e.g., 3rd Feb is 34th day of year)
static char daytab[2][13] = { // [row][col]
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, // leap year
}; // a 2-D array declared and initialized.

/* day_of_year: set day of year from month & day*/


int day_of_year(int year, int month, int day) {
int i, leap;
leap = (year%4 == 0 && year%100 != 0) || (year%400 == 0);
for (i = 1; i < month; i++)
day += daytab[leap][i];
return day;
} 26
CSE, BUET CSE-105 – Structured Programming
Multi-dimensional Array (K R 5.7) n

Example: Date conversion problem


month_day
Input: year, yearday( i.e., day of the year)
Output: month, day (e.g., 34th day is 3rd Feb)
static char daytab[2][13] = { // [row][col]
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, // leap year
};
/* month_day: set month, day from day of year */
void month_day(int year, int yearday, int *pmonth, int *pday) {
int i, leap;
leap = (year%4 == 0 && year%100 != 0) || (year%400 == 0);
for (i = 1; yearday > daytab[leap][i]; i++)
yearday -= daytab[leap][i];
*pmonth = i;
*pday = yearday;
} 27
CSE, BUET CSE-105 – Structured Programming
Multi-dimensional Array (K R 5.7) n

In function parameter only the left most dimension is


unnecessary.
Thus all the following are equivalent:
void func(int daytab[2][13]) { … }
void func(int daytab[][13]) { … }
void func(int (*daytab)[13]) { … }
The brackets in last statement is necessary since [ ] have
higher precedence than *.
int (*daytab)[13] : a pointer to an array of 13 elements
0 12
daytab

int *daytab[13] : daytab[0]

an array of 13 pointers to integers. [1]

[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” };

name is an array of character pointers


For each initializer string a character array is created and a
pointer to that string is placed in name array.
Since no size is specified, the compiler counts the number of
initializer strings and fills in the correct number.
name[0] illegal month\0
[1] January\0

[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 20row+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

char aname[][15] = {“illegal”, “Jan”, “Feb”, “Mar” };


aname:

illegal\0 Jan\0 Feb\0 Mar\0


0(4200) 15(4215) 30(4230) 45(4245)
aname[i][j] is calculated as (aname + 15  i + j)
aname has no LValue
char *name[] = {“illegal”, “Jan”, “Feb”, “Mar” };
name[i][j] is calculated as
(name + sizeof(char *)  i name[0] illegal\0

+ j * sizeof(char)) [1] Jan\0

name has no LValue [2] Feb\0


char **pname; [3] Mar\0
Allocates only 1 pointer (i.e., 2/4 bytes)
pname[i][j] is calculated as pname string\0

(*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

main is called with two arguments :


int argc: is the number of command-line arguments
char **argv: pointer to array of strings (i.e., char *)
int main(int argc, char **argv)
echo.c invoked with: echo hello world
argc is 3 and argv is  argv [0] echo\0
[1] hello\0

#include <stdio.h> [2] world\0

int main(int argc, char **argv) { [3] 0

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

main is called with two arguments :


int argc: is the number of command-line arguments
char **argv: pointer to array of strings (i.e., char *)
int main(int argc, char **argv)
echo.c invoked with: echo hello world
argc is 3 and argv is  argv [0] echo\0
[1] hello\0

#include <stdio.h> [2] world\0


[3] 0
int main(int argc, char **argv) {
while (--argc > 0)
printf(argc>1? “%s ” : “%s”, *++argv);
return 0;
}
33
CSE, BUET CSE-105 – Structured Programming
Comman-line Arguments (K R 5.10) n

/* Processing command-line options: like –abc –x –v */


int main(int argc, char **argv) {
while (--argc > 0 && (*++argv)[0] == ‘-’) { // each option group
while (c = *++argv[0]) { // for each option in the goup
// process the option
}
}
} find.exe\0
argv

(*++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

/* Processing command-line options: like –abc –x –v */


int main(int argc, char **argv) {
while (--argc > 0 && (*++argv)[0] == ‘-’) { // each option group
while (c = *++argv[0]) { // for each option in the group
// process the option
}
}
} find.exe\0
argv
++argv[0]
argv[0]
- x f r \0

0 *++argv[0]

-m\0

35
CSE, BUET CSE-105 – Structured Programming
Complicated Declarations (K R 5.12) n

Read C declarations using a counter-clock wise spiral


Do not cross a bracket (**a[]) unless all the tokens within
the bracket are finished

int *f() int * f () f is a function returning int *

int (*f)() int ( * fp ) () fp is a pointer tofunction returning int

36
CSE, BUET CSE-105 – Structured Programming
Complicated Declarations (K R 5.12) n

char (*(*x())[5])()

char ( * ( * x () ) [5] ) ()

x is a function returning pointer to array[5] of pointer to function returning char

char (*(*x[3])())[5]

x is a array[3] of pointer to function returning pointer to array[5] of char


37
CSE, BUET CSE-105 – Structured Programming
Examples
int *f();
f: function returning pointer to int
int (*pf)();
pf: pointer to function returning int
int (*daytab)[13]
daytab: pointer to array[13] of int
int *daytab[13]
daytab: array[13] of pointer to int

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. il1 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. ii+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 ]
il1
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; ii+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

void qsort(char *A[], int l, int r) {


int i, j, q;
void swap(char **pa, char **pb);
if (l < r) {
for (i = l-1, j = l; j <= r-1; j++)
if (strcmp( A[j], A[r]) <= 0)
swap( &A[++i], &A[j]);
swap( &A[i+1], &A[r]);
q = i+1;
qsort( A, l, q-1);
qsort( A, q+1, r);
}
}
void swap(char **pa, char **pb) {
char *temp;
temp = *pa;
*pa = *pb;
*pb = temp;
}

43
CSE, BUET CSE-105 – Structured Programming
Pointers to Functions (K R 5.11) n

void qsort(void *A[], int (*comp)(void *, void *),


int l, int r) {
int i, j, q;
void swap(void **pa, void **pb);
if (l < r) {
for (i = l-1, j = l; j <= r-1; j++)
if ((*comp)(A[j], A[r]) < 0)
swap(&A[++i], &A[j]);

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

void qsort(void *v[], int (*comp)(void *, void *),


int left, int right);
// in main function

qsort(lineptr, comp_str, 0, 10); // char *lineptr[];


qsort(intptr, comp_int, 0, 10); // int *intptr[];

45
CSE, BUET CSE-105 – Structured Programming
Pointers to Functions (K R 5.11) n

In C, a function itself is not a variable


But pointer to function can be created
int (*comp)(void *, void *)
comp is a pointer to function that returns int and takes
two void * type arguments
BEWARE: int *comp(void *, void *)
means that comp is a function that returns int * and
takes two void * type arguments
int result = (*comp)(&x, &y)
invokes comp with parameters x and y

46
CSE, BUET CSE-105 – Structured Programming

You might also like