You are on page 1of 52

Chapter 8

Pointers

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 2

Chapter Contents
 Why pointers?
 Pointers what are they?
 Pointers- declaration, assignment, display
 Pointer pitfalls
 Pointers and arrays
Arithmetic operations on pointers
Comparison of pointers
Scanning arrays using pointers
 Pointers and functions
 Passing variables by reference
 Class exercise
 Summary
 Exercises
 Arguments to Function main()

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 3

Why Pointers?
 Remember scanf ? We sent it a variable, and it filled it with
information from the standard input. scanf actually changed the
variable that we sent as a parameter. How did it do it ?…

 As you know, sending a variable to scanf included an & before the


variable name.
The variable was sent by reference, rather than by value.
In other words –
We sent the address of the variable.

 In C, there is a special variable type, called pointer.

 A pointer holds the address of another variable.


We shall use pointers for passing variables by reference, but
also for :
A rapid scan of arrays.
Dynamic memory allocation (in the next chapter).

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 4

Pointers – What Are They?


 Every variable has an address and a value.
FFD8
For example : FFD7
int a = 5; FFD6
5 a
FFD5
FFD4
FFD3
 C has two operators, & (address of) and * (indirection),
used with pointers:

& Gives the address of a variable (&a == FFD4).


* has 2 different meanings :
 Upon declaration – ‘I am a pointer’ ( example: int *p;).
 After declaration – the variable whose address is held by the pointer
 Examples:
*ptr = 3;
printf(“%d”, *ptr);
scanf(“%d”, ptr);
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 5

Pointer Declaration

int *px; px is :
type – a pointer to int.
px ? ? size – 2/4 bytes.
value – currently ‘garbage’.

float *pf; pf is :
pf ? ? type – a pointer to float.
size – 2/4 bytes.
value – currently ‘garbage’.

char *pc1, *pc2;


pc1 and pc2 are :
pc1 ? ? type – pointers to char.
size – 2/4 bytes.
pc2 ? ?
value – currently ‘garbage’.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 6

Assigning a Value to a Pointer


 int a = 5; a is an int, initialized to 5. It has an
address.
a
5

 int
p *p; p is a pointer to an int,
? currently contains ‘garbage’.

 p p = &a; p holdsa the address of a. p points to a.


FFD5 5

 *p is the variable that p points to. In other words, *p is a.

 There are 2 ways to access a : via a, via p.

© Copyright: Spymek Software Pvt. Ltd.


Assigning a Value to a Pointer
C1 Ch03 - Operators and Expressions – 7

– cont’d
 A pointer can hold the address of a variable of the same type as
it was defined to point to.

 Example:

int i, *i_ptr1 = NULL, *i_ptr2 = NULL;


double d, *d_ptr = NULL;

i_ptr1 = &i; /* i_ptr1 holds the address of i */


i_ptr2 = i_ptr1; /* now i_ptr2 also points to i
*/
d_ptr = &d; /* d_ptr holds the address of d */

 As a special case, a pointer can be assigned the value NULL


(defined to be zero).
A NULL pointer means – not pointing to anything, illegal
address.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 8

Example: pointer.c
1 /* pointer.c
2 This program illustrates pointers (declaration, initialization
3 and indirection) */
4 #include <stdio.h>
5
6 void main(void)
7 {
8 int i = 1;
9 char c = 'a';
10 int *Pi = NULL; /* pointer to int, initialized with NULL.
*/
11 char *Pc = NULL;/* pointer to char, initialized with
NULL.*/
12
13 printf("Address of i (&i): %p. Value of i (i): %d\n" ,
14 &i, i);
15 printf("Address of c (&c): %p. Value of c (c): %c\n" ,
16 &c, c);
17 putchar('\n');
18 printf("Address of Pi (&Pi): %p. Value of Pi (pi):"
19 "%p\n",&Pi,Pi);
20 printf("Address of Pc (&Pc): %p. "
21 "Value of Pc (pc):%p\n",&Pc,Pc);
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 9

Example: pointer.c – cont’d


22 Pi = &i;/* Pi holds the address of i. i is the value of Pi */
23 Pc = &c;/* Pc holds the address of c. c is the value of Pc */
24 *Pi = 2; /* *Pi is actually i. i was assigned the value 2
*/
25 *Pc ='b';/* *Pc is actually c. c was assigned the value
'b'*/
26
27 ++i; /* i is now 3. */
28 ++c; /* c is now 'c' */
29 putchar('\n');
30 printf("Address of i (&i): %p. Value of i (i): %d\n" ,
31 &i, i);
32 printf("Address of c (&c): %p. Value of c (c): %c\n" ,
33 &c, c);
34 putchar('\n');
35 printf("Address of Pi (&Pi): %p. Value of Pi (pi):"
36 "%p\n", &Pi,Pi);
37 printf("Address of Pc (&Pc): %p. Value of Pc (pc):"
38 " %p\n",&Pc,Pc);
39 putchar('\n');
40 /* *Pi is actually i and *Pc is actually c */
41 printf("The value of Pi (*Pi) : %d\n", *Pi);
42 printf("The value of Pc (*Pc) : %c\n", *Pc);
43 } © Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 10

Pointers Pitfalls
 Assigning the wrong type of address:

int *ip = NULL;


double d, *dp = NULL;
dp = &d; /* o.k */
ip = &d; /* wrong (warning) */
ip = dp; /* wrong (warning) */
ip = &dp;/* wrong (warning) */

 Assigning wrong values to pointers:

int *ip = NULL;


ip = 1; /* wrong (warning) */

( ip = 0; is legal, it is like ip = NULL; )

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 11

Pointers Pitfalls – cont’d


 Illegal use of a pointer:

int i,*ip = NULL;


*ip = 3; /* wrong */
ip = &i; /* right */
*ip = 3; /* right */

 This kind of mistake can be avoided by checking whether the


pointer is still NULL (‘invalid’ pointer) before using the
indirection operator on it.
if(ip)
{
*ip = 3;
}

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 12

Pointers and Arrays


 The name of an array is a pointer to element #0 of the array.

int a[100];
int *ptr = a;
printf("%p %p", a, ptr); /* the same address */

The address of the element with index 0 will be held by ptr;


In other words, ptr will point to the beginning of the array.

 In order to scan arrays with pointers we must know :

Memory layout of arrays.


Pointers arithmetic.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 13

Pointers and Arrays – cont’d


 Memory Layout
An array is a consecutive piece of memory.

int v[3]; /* 3 * sizeof(int)


consecutive bytes */

float f[1000]; /* 1000 * sizeof(float)


onsecutive bytes */

 If there is not enough consecutive memory for our array, we will


simply not get it…

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 14

Pointers and Arrays – cont’d


 Pointer Arithmetic

There are some arithmetic operations that may be performed on


pointers.

 Add/subtract a whole number to/from a pointer.

char arr[10];
char *char_ptr = arr; /* will scan arr successfully */
double *double_ptr = arr; /* will not work very well… */
arr

? ? ? ? ? ? ? ? ? ?

char_ptr double_ptr
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 15

Pointers and Arrays – cont’d


++char_ptr; /* adds 1 to char_ptr */
++double_ptr; /* adds 8 to double_ptr */

char_ptr
? ? ? ? ? ? ? ? ? ?

double_ptr

 When we add/subtract a whole number to/from a pointer, the


computer adds/subtracts that number multiplied by sizeof the
pointers type.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 16

Pointers and Arrays – cont’d

 When scanning arrays with indexes we write:


float arr[5];
arr[2] = 3.3;

 The compiler sees :


float arr[5];
*( arr + 2 * sizeof(float) ) = 3.3;

 It is the programmer’s responsibility to keep the pointer within


the borders of the array, just like when scanning arrays with
indexes.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 17

Pointers and Arrays – cont’d

 Two pointers to objects of the same type, in the same array,


may be subtracted.
The result is the number of indexes (not the number of bytes !)
between them.

If, for instance, p1 points to the beginning of a string and p2


points to the null terminator of this string, then p2 - p1 gives the
string's length.

 Addition of pointers is meaningless.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 18

Pointers and Arrays – cont’d


 Comparing pointers

Two pointers, may be compared, if they point to the same


type.
Any pointer may be compared to NULL (zero).

Examples:

int *p1 = NULL, *p2 = NULL;


if (p1 == p2)
if (p1 < p2)
if (p1 != NULL)

 A good programmer checks the validity of a


pointer before using the indirection operator on
it.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 19

Pointers and Arrays – cont’d


 As seen before, we may declare :

int a[100];
int *p = a;

 All the expressions in each line mean the same :


a,&a[0],p,&p[0] address of the first element (index 0)

*a,a[0],*p,p[0] the first element (index 0)

a+1,&a[1],p+1,&p[1] address of the 2’nd element (index 1)

*(a+1),a[1],*(p+1),p[1] the 2’nd element (index 1)

a+i,&a[i],p+i,&p[i] address of the i+1 element (index i)

*(a+i),a[i],*(p+i),p[i] the i+1 element (index i)

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 20

Pointers and Arrays – cont’d


 Attention !
p++;
p=p+5; etc. are perfectly legal,

BUT
arr++;
arr=arr+5; etc. are illegal, since arr was defined as an array.
 Question :
Is the following code legal ? Why ?

void func(int ptr[])


{
++ptr;
}
void main(void)
{
int arr[10];/*the statement ++arr will not
compile*/ func(arr);
}
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 21

Mixed Pointer Operations


 Given that:

int k, *ptr = NULL;


int Arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
ptr = Arr;
What is the meaning of k = *ptr++; ?

 k = *ptr++ is equivalent to the following two statements

k = *ptr;
ptr++;

 What is the meaning of :


k = (*ptr)++;
k = *(ptr++);
k = *++ptr;
k = ++*ptr;
 Try to avoid such unreadable coding, even if it is works !
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 22

Scanning Arrays Using Pointers


 Scanning arrays using pointers is faster than scanning them
using indexes. Here are two functions that perform the same job:

 First function:
Uses indexes to sum the n first elements of the array v.

long scan_with_indexes(int v[], int n) /* int v[] =


int *v
*/
{
int i = 0; The operations
long total = 0;

while(i < n) <


{
total += v[i]; += *(v + i*sizeof(int))
++i; ++
}
return total;
} © Copyright: Spymek Software Pvt. Ltd.
Scanning Arrays Using Pointers
C1 Ch03 - Operators and Expressions – 23

– cont’d
 Second Function:
Uses pointers to sum the n first elements of the array v.

long scan_with_pointers(int *v, int n)


{
long total = 0; The operations
int *save_end = v+n;
while(v < save_end) <
{
total += *v; += *(indirection)
++v; ++
}
return total;
}

 Conclusion :
Each iteration of scanning with indexes involves a multiplying action and
an addition action that are not necessary when scanning with pointers.
scan_with_pointers() is faster than scan_with_indexes().

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 24

Example: pointer-scan.c
1 /* pointer-scan.c
2 This program illustrates scanning arrays with pointers.
3 What will be the output of the following program ? */
4
5 #include <stdio.h>
6
7 void main()
8 {
9 int arr[10] = {0}; /* an array of 10 ints, all initialized
10 to 0 */
11 int *p_start = NULL,*p_end=NULL; /* 2 pointers to int */
12 int i; /* counter */
13
14 p_start = arr;/*p_start points to the first element of
arr*/
15 p_end = &arr[9];/*p_end points to the last element of
arr*/
16
17 /* assign values to each element of the array.The array is
18 scanned using the pointer p_start */
19
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 25

Example: pointer-scan.c – cont’d


20 for( i = 0 ; i < 10 ; ++i )
21 {
22 *p_start = i;
23 ++p_start;
24 }
25 /* p_start is now holding the address of the LAST element of
26 the array. Set it to point to the first element */
27 p_start = arr;
28

29 /* print every other element of the array, from the last


30 element to the first, using the pointer p_end.
31 Instead of looping 5 times, loop as long as the pointer
p_end
32 points to an address higher than or equal to the address
33 pointed by the pointer p_start */
34

35 while(p_end >= p_start)


36 {
37 printf("%d ", *p_end);
38 p_end -= 2;
39 }
40 }
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 26

Pointers and Functions


 How can we change the value of a parameter sent to a
function ?

 How can a function return a lot of information to the calling


function ?…
After all, there is only one return value…

 The solution is ……
Sending the address of the variable causes the variable to be
sent by reference rather than by value.
The function will receive a pointer to the variable and will be
able to change it.

int num, *ptr = &num;

func(&num);
func(ptr);
The same
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 27

Pointers and Functions – cont’d


 If we pass the variable i to a function, we actually pass the value of
i.

 If we pass the address of i, we actually pass a pointer to i.

 The pointer is passed by value, of course, there is no other way…


BUT

 The value that is passed is the address of i, so the pointer that the
function received as a parameter actually points to i.

 The function can change i via the pointer that it received as a


parameter.

 Note:
When we passed an array to a function we actually passed the
address of the array (where it begins) - a pointer.
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 28

Swapping Values
 Here are two programs. Each of them tries to swap the values
of two variables :

What is the output of each program?

In the first program the parameters are sent by value (the usual
way…)

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 29

Swapping Values – cont’d


1 /* swap1.c */
2 #include <stdio.h>
3 void swap(int x, int y)
4 {
5 int temp;
6 temp = x;
7 x = y;
8 y = temp;
9 }
10
11 void main(void)
12 {
13 int a = 3, b = 2;
14 printf("Before swapping : a=%d b=%d\n", a, b);
15 swap(a,b); /* send a and b by value */
16 printf("After swapping : a=%d b=%d\n", a, b);
17 }
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 30

What did the program do ?


main()
main() calls swap() returns
swap() FFA2 a = 3 to main()

FFB2 b = 2

swap (int x, int y)

FABA x = 3 swapping FABA x = 2


FACC y = 2 FACC y = 3

 In other words, it did nothing...

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 31

Swapping Values – by Reference


 In the second program the parameters are sent by reference.
1 /* swap2.c */
2 #include <stdio.h>
3 void swap(int *x, int *y)
4 {
5 int temp;
6 temp = *x;
7 *x = *y;
8 *y = temp;
9 }
10
11 void main(void)
12 {
13 int a = 3, b = 2;
14 printf("Before swapping : a=%d b=%d\n", a, b);
15 swap(&a, &b); /* send a and b by reference */
16 printf("After swapping : a=%d b=%d\n", a, b);
17 }

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 32

What Did the Program Do ?


main()
main() calls swap() returns
swap() FFA2 a = 3 to main()

FFB2 b = 2

swap (int *x, int *y)


FABA x= FFA2
FACC y=FFB2

swapping
FFA2 *x = 3 FFA2 *x = 2
FFB2 *y = 2 FFB2 *y = 3

 The values of a and b have been swapped !


© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 33

Example: arrange_arr.c
1 /* This program sorts an array of characters so that the characters
2 will be in increasing order. It uses pointers only,no indexes.*/
3
4 #include <stdio.h>
5 /* prototypes */
6 void print_arr(const char *arr, int len);
7 void rearrange_arr(char *arr, int len);
8 void swap(char x[], char y[]);
9
10 void main(void)
11 {
12 char arr[] = {'p', 'o', 'p', 'y', 'f', 'l'};
13 int length = sizeof(arr) / sizeof(char);
14 printf("Before rearranging the elements of the array
"
15 ":\n");
16 print_arr(arr, length);
17 rearrange_arr(arr, length);
18 printf("After rearranging the elements of the array "
19 ":\n");
20 print_arr(arr, length);
21 }
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 34

Example: arrange_arr.c – cont’d


22 /* This function rearranges the array. It uses bubble sort.
23 (The highest value ‘climbs’ up to the top) */
24 void rearrange_arr(char arr[], int len)
25 {
26 char *p1 = NULL,*p2 = NULL;/* pointers for scanning arr */
27 char *p_end = &arr[len -1]; /* pointer to the last element
28 of arr */
29

30 p1 = p2 = arr; /* the 2 pointers point to the first element


31 of arr */
32 p1++; /* one pointer points to one element forward than the
33 other */
34

35 /* the following lines perform a bubble sort on the array */


36 while(p1 <= p_end)
37 {
38 p2 = arr;
39

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 35

Example: arrange_arr.c – cont’d


40 while(p2 < p1)
41 {
42 if(*p1 < *p2)
43 swap(p1, p2);
44 ++p2;
45 }
46 ++p1;
47 }
48 }
49 /* this function prints the array */
50 void print_arr(const char *arr, int len)
51 {
52 char *p_start = arr;/*pointer to the first element of arr*/
53 char *p_end = &arr[len-1]; /* pointer to the last element
54 of arr */
55
56 /* loop until p_start points to the last element of
57 arr(inclusive) */
58

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 36

Example: arrange_arr.c – cont’d


59 while(p_start <= p_end)
60 {
61 printf("%c", *p_start); /*print the char that
62 p_start points to*/
63 ++p_start; /*p_start points to the next element*/
64 }
65 printf("\n\n");
66 }
67
68 /* this function swaps the values of two pointers */
69 void swap(char x[], char y[])
70 {
71 char tmp;
72
73 tmp = *x;
74 *x = *y;
75 *y = tmp;
76 }

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 37

Example: char-del.c
1 /* char-del.c
2 This program does the same thing as the program char_del.c in
3 chapter 6. It deletes all the occurrences of a certain character
4 from a string. The difference between the two programs is that
5 in chapter 6 we used indexes for scanning the array, and here we
6 use pointers. */
7

8 #include <stdio.h>
9 #include <string.h>
10

11 void main(void)
12 {
13 char s[128]; /* the string will be entered by the user */
14 char *p1, *p2; /* the pointers for scanning the array */
15 int ch; /* the character to delete from the string */
16 unsigned int savelen; /* length of the original string */
17

18 printf("This program gets a string and a character.\


n"
19 "It deletes all the occurrences of the character "
20 "from the string.\n");
21 printf("Enter a string => ");
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 38

Example: char-del.c – cont’d


22 gets(s);
23 savelen = strlen(s); /* save the original length of the
24 string */
25 printf("Enter a character => ");
26 ch = getchar();
27
28 for (p1 = p2 = s ; *p1 ; ++p1)
29 {
30 if (*p1 != ch)
31 {
32 *p2 = *p1;
33 ++p2;
34 }
35 }
36 *p2 = '\0'; /* if s contained ch, s in now shorter. We are
37 responsible for placing a null terminator at the new
38 end of s*/
39

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 39

Example: char-del.c – cont’d


40 if(savelen == strlen(s))
41 printf("'%c' does not occur in the"
42 "string\n",ch);
43 else
44 {
45 printf("The character '%c' was"
46 "deleted %d times.\n"
47 "The new string is: %s\n", ch,
48 savelen-strlen(s), s);
49 /* Instead of writing savelen-strlen(s) we could
have
50 written savelen - (p2 - s); */
51 }
52 }

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 40

Example – String Length

int strlen(const char *s)


{
Version 1 :
int n;
for(n = 0; *s ; ++s)
++n;
return(n);
}

int strlen(const char *s)


{
char *ptr = s;
Version 2 : while(*ptr)
++ptr;
return(ptr-s);
}

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 41

Example – String Copy


 Here are two versions of the function strcpy().
void strcpy(char s[], char t[])
{
using indexes : int i=0;
while((s[i] = t[i]) != '\0')
i++;
}

void strcpy(char *s, char *t)


{
while((*s = *t) != '\0')
{
using pointers : s++;
t++;
}
}
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 42

Class Exercise
 Example :

void main(void)
{
char arr[][10]={"This","is","a","short","example"};
printf("%c", arr[0][1]); /* 'h' */
printf("%c", *arr[4]); /* 'e' */
printf("%c", (*(arr + 4))[5]); /* 'l' */
printf("%c", *(arr[4] + 3) - 1); /* 'l' */
printf("%c", (arr + 3)[0][2]); /* 'o' */
printf("%c", '\n'); /* '\n' */
}
void main(void)
{
char arr[][10] = {"It's", "wide", "and", "wonderful"};
printf("%c", *((arr + 1)[0]));
printf("%c", *(arr[3] + 1));
printf("%c", (*arr)[3] - 1);
printf("%c", arr[3][strlen(arr[3])-1]);
printf("%c", *arr[2] + 3);
printf("%c", '\n');
}

If you survived this, pointers are your best friends !!!


© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 43

Summary
 A pointer is a variable that holds the address of another variable.

 A pointer can be assigned the address of a variable of the same


type as it was defined to point to.

 If the pointer is not pointing to a variable, make it point to NULL.

 Addition/subtraction of a whole number to/from a pointer is


allowed. The number added/subtracted is first multiplied (by the
computer) by the size of what the pointer was defined to point to.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 44

Summary – cont’d
 Subtraction (but not addition) of pointers gives the number of
indexes between them.

 Pointers to the same type may be compared. Any pointer may


be compared with NULL.

 The name of an array is actually a pointer to its element #0.


Arrays are scanned faster using pointers than using indexes.

 Pointers enable us to pass variables to functions by


reference.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 45

Exercises
1 Write a program that:
Requests and reads a string.
Requests and reads a character and informs whether the
character occurs in the string.
Requests and reads another character and informs whether the
character occurs in the string.
If both characters occur in the string, print a message to inform
which one of them precedes the other, and the distance
between the first occurrence of each of them.
Use library function strchr( ).

2 Write a function that copies the first n elements of one array to


another one, using pointers. Write main( ) to call the function.

3 Write a version of strcat() that works with pointers instead of


array's indexes. (cf . chapter 7).

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 46

Exercises – cont’d
4 Write a version of strcmp(char *str1, char *str2)
that works with pointers, which compares (lexicographically)
two strings and returns int value as follows:
<0 If str1 < str2
=0 If str1 ==str2
>0 If str1 >str2

5 Write a function chs( int * ) that changes the sign of its


argument. (Note that return type is void).

6 Write a function: int index( char *src, char *str)


that finds the first occurrence of the string str in the string src.
The function returns the position in src where str was found.
If not found it returns some negative number.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 47

Example: memory-game.c
1 /*This program illustrates the memory game. 4 pairs of numbers are
2 placed on a game board.When a pair is found,it turns to smileys. */
3

4 #include <stdio.h>
5 #define TRUE 1
6 #define FALSE 0
7 #define SMILEY 1 /* 1 is the ASCII of the smiley character */
8
9 void print(const char *plast1,const char *plast2,const
10 char mat[3][3]);
11 int play(char mat[3][3]);
12 int check_win(const char mat[][3]);
13 int check_and_change(char *ptr_num1, char *ptr_num2);
14 void get_coordinates(int *row1, int *col1, int *row2,
15 int *col2);

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 48

Example: memory-game.c – cont’d


16 void main(void)
17 {
18 char mat[3][3] = {'1', '2', '3', '4', SMILEY,
19 '4','3', '2', '1'};
20 int num_guesses = 1; /* counts the user’s tries before
21 winning */
22 while(play(mat) == FALSE) /* play returns TRUE if the user
23 wins */
24 num_guesses++; /* increase the number of the user’s tries */
25 printf("\nYou won ! It took %d guesses.\n",
26 num_guesses);
27 }
28 int play(char mat[3][3])
29 {
30 int row1, col1, row2, col2; /*the coordinates for the
31 user's guess*/
32 int success = FALSE;
33 /* call a function that gets 4 legal coordinates (for 2
34 locations) */
35

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 49

Example: memory-game.c – cont’d


36 get_coordinates(&row1, &col1, &row2, &col2);
37 /*check the guess, put smileys if the guess was right. */
38 success = check_and_change(&mat[row1][col1],
39 &mat[row2][col2]);
40 if(success)/* if the guess was right, perhaps the user won
*/
41 success = check_win(mat);
42 print(&mat[row1][col1], &mat[row2][col2], mat);
43 return (success);/* TRUE if the user won, FALSE otherwise
*/
44 }
45 /*print the board. Put a smiley on solved locations, reveal the
46 numbers of the last guessed locations, print '?' at any other
47 location. */
48 void print(const char *pLast1, const char *pLast2, const
49 char mat[3][3])
50 {
51 char *ptr = NULL;
52 int ctr = 0;
53

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 50

Example: memory-game.c – cont’d


54 for(ptr = &mat[0][0], ctr = 0 ; ptr <= &mat[2][2] ;
55 ++ptr, ++ctr)
56 { /* go through every location on the board*/
57 if(ctr && !(ctr % 3)) /* print 3 items per line */
58 putchar('\n');
59 if(*ptr == SMILEY || ptr == pLast1 || ptr ==
60 pLast2)
61 printf("%3c", *ptr);
62 else
63 printf("%3c", '?');
64 }
65 }
66 int check_and_change(char *ptr_num1, char *ptr_num2)
67 { /* if the numbers match,replace them with smileys and return TRUE */
68 if( (*ptr_num1 !=*ptr_num2) || (*ptr_num1 == SMILEY) )
69 return (FALSE);
70 return(*ptr_num1 = *ptr_num2 = SMILEY);
71 /* assignment AND return */
72 }
73

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 51

Example: memory-game.c – cont’d


74 int check_win(const char mat[][3])
75 {
76 char *p = NULL;
77 /* the loop may end because :
78 1) the whole board was checked - the user won.
79 2) a location was not a smiley - the user didn’t win yet.
*/
80 for(p = &mat[0][0] ; (p <= &mat[2][2]) && (*p ==
81 SMILEY) ; +
+p)
82 { }
83 return (--p == &mat[2][2]);
84 }
85 int legal(int coord)
86 {/* returns 1 if the coordinate is in the borders of the matrix */
87 return (coord >= 0 && coord <= 2);
88 }

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 52

Example: memory-game.c – cont’d

89 void get_coordinates(int *row1, int *col1, int *row2,


90 int *col2)
91 {
92 do {
93 printf("\nEnter 4 coordinates (x1 y1 x2 y2)=>
");
94 scanf("%d%d%d%d", row1, col1, row2, col2);
95 }while(!(legal(*row1) && legal(*col1) &&
legal(*row2)
96 && legal(*col2)));
97 }

© Copyright: Spymek Software Pvt. Ltd.

You might also like