Professional Documents
Culture Documents
Pointers
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()
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 ?…
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’.
int
p *p; p is a pointer to an int,
? currently contains ‘garbage’.
– cont’d
A pointer can hold the address of a variable of the same type as
it was defined to point to.
Example:
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
Pointers Pitfalls
Assigning the wrong type of address:
int a[100];
int *ptr = a;
printf("%p %p", a, ptr); /* the same address */
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
char_ptr
? ? ? ? ? ? ? ? ? ?
double_ptr
Examples:
int a[100];
int *p = a;
BUT
arr++;
arr=arr+5; etc. are illegal, since arr was defined as an array.
Question :
Is the following code legal ? Why ?
k = *ptr;
ptr++;
First function:
Uses indexes to sum the n first elements of the array v.
– cont’d
Second Function:
Uses pointers to sum the n first elements of the array v.
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().
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
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.
func(&num);
func(ptr);
The same
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 27
The value that is passed is the address of i, so the pointer that the
function received as a parameter actually points to i.
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 :
In the first program the parameters are sent by value (the usual
way…)
FFB2 b = 2
FFB2 b = 2
swapping
FFA2 *x = 3 FFA2 *x = 2
FFB2 *y = 2 FFB2 *y = 3
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: 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
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');
}
Summary
A pointer is a variable that holds the address of another variable.
Summary – cont’d
Subtraction (but not addition) of pointers gives the number of
indexes between them.
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( ).
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
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);