Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
52 views39 pages

Chap-2-Data Handling

It is good for understanding data handling, since data is a crucial thing as privacy is concerned.so feel free to download it

Uploaded by

kiokocurtis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views39 pages

Chap-2-Data Handling

It is good for understanding data handling, since data is a crucial thing as privacy is concerned.so feel free to download it

Uploaded by

kiokocurtis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 39

Pointers

 Objectives
 At the end of this chapter, the reader should be

able to:
 Define a pointer
 Declare pointer variables
 Use basic pointer operators * and &
 Understand operations permitted with pointers
 Use pointers with arrays
 Use pointers with string variables

Jane Kuria Inoorero University 07/05/24


Introduction
2

 This chapter covers one of C’s most important and


sometimes most troublesome features: the pointer.
 A pointer is basically an address of an object. One
reason that pointers are so important is that much
of the power of the C language is derived from the
unique way in which they are implemented.
 You will learn about special pointer operators,
pointer arithmetic and how arrays and pointers are
related.

Jane Kuria Inoorero University 07/05/24


Revision
3

A variable has a name, an address, a type, and a value:


 "the name identifies the variable to the programmer

 "the address specifies where in main memory the

variable is located (i.e., the beginning of the memory


region reserved for this variable )
 "the type specifies how to interpret the data stored in

main memory and how long the variable is


 "the value is the actual data stored in the variable after

if has been interpreted according to a given type

Jane Kuria Inoorero University 07/05/24


Pointer defined
4

 A pointer is a variable that holds the memory address of


another variable.

 Pointers are language constructs that allow programmers to


directly manipulate the address of variables

 For example, if a variable called p contains the address of


another variable called q, then p is said to point to q.

 Therefore if q were at location 100 in memory, then p


would have the value 100.
Jane Kuria Inoorero University 07/05/24
Pointer defined
5

Pointers are used with the * and & operators:

 int* px; /*px = pointer to an integer*/


 int x; /*x is an integer */
 px = &x; /* px gets the address of x */
 /* or px points to x */
 x = *px; /* x gets the contents of */
 /* whatever x points to */

 View diagrams

Jane Kuria Inoorero University 07/05/24


Pointer declaration
6

 To declare a pointer variable, use this general form:


 type *var_name;

 Here, type is the base type of the pointer. The base type
specifies the type of the object that the pointer can point to.
 Notice that an asterisk precedes the variable name. This
tells the computer that a pointer variable is being created.
 For example, the following statement creates a pointer to an
integer.

 int *p;
Jane Kuria Inoorero University 07/05/24
Pointer Operators
7

 C contains two special pointer operators: * and &.


 The & operator returns the address of the variable
it precedes.
 The * operator returns the value stored at the
address that it precedes.
 The * pointer operator has no relationship to the
multiplication operator, which uses the same
symbol).

Jane Kuria Inoorero University 07/05/24


Example
8

1. #include<stdio.h>
2. main()
3. {
4. int *p, q;
5. q = 100; /* assign q 100 */
6. p = &q; /* assign p the address of q*/
7. printf(“%d”, p);
8. /* display q’s value using pointer*/
9. return 0;
10. }

Jane Kuria Inoorero University 07/05/24


Explanation
9

 This program prints 100 on the screen. Let us see why.

 First, the line int *p, q; defines two variables: p, which is


declared as an integer pointer, and q, which is an integer.
Next, q is assigned the value 100.

 In the next line, p is assigned the address of q. You can


verbalize the & operator as “address of.“
 Therefore, this line can be read as: assign p the address of
q.
 Finally, the value is displayed using the * operator applied
to p. The * operator can be verbalized as “at address”.

Jane Kuria Inoorero University 07/05/24


Explanation…
10

 Therefore the printf( ) statement can be read as


“print the value at address q,” which is 100.

 When a variable value is referenced through a


pointer, the process is called indirection.

 It is possible to use the * operator on the left side


of an assignment statement in order to assign a
variable a new value using a pointer to it.
Jane Kuria Inoorero University 07/05/24
Example
11

 This program assigns a value q indirectly using the pointer p.

1. #include<stdio.h>
2. main()
3. {
4. int *p, q;
5. p = &q; /* get q’s address */
6. p = 199; /* assign q a value using a pointer */
7. printf(“q’s value is %d”, q);
8. return 0;
9. }

10. Note: The type of the variable and type of pointer must match.

Jane Kuria Inoorero University 07/05/24


Example
12

 This program uses pointers to display the values of a loop counter.

1. #include<stdio.h>
2. main()
3. {
4. int i,*p;
5. p = &i;
6. for (i =0; i <10; i++)
7. printf (“%d\n”, *p);
8. return 0;
9. }

Jane Kuria Inoorero University 07/05/24


Example
13

 The following program performs some basic arithmetic using pointers.

1. #include<stdio.h>
2. main()
3. {
4. int u1, u2;
5. int v = 3;
6. int *pv;
7. u1 = 2 * ( v + 5 );
8. pv = &v;
9. u2 = 2 * (*pv + 5 );
10. printf(“ \n u1 = %d u2 = %d ”, u1, u2);
11. return 0;
12. }

Jane Kuria Inoorero University 07/05/24


Output
14

Jane Kuria Inoorero University 07/05/24


Pointers operations
15

 It is possible to perform several operations with pointer


variables as explained below.

 Assignment

 One can assign an address to a pointer by:


 Using an array name or
 Using the address operator

 From the previous example, p1 is assigned the address


of the beginning of the array which is cell 234.
Jane Kuria Inoorero University 07/05/24
Dereferencing (value – finding)
16

 The * operator gives the value pointed to.

 From the previous example, p1 = 100 which is the value


stored in location 234.

 Taking a pointer address

 Pointer variables have an address and a value. The &


operator tells us where the pointer itself is stored.

 From the previous example, p1 is stored in address 3606


whose value is 234.
Jane Kuria Inoorero University 07/05/24
Pointer arithmetic
17

 In general, pointers may be used like other


variables.
 However, you need to understand a few rules and
restrictions.
 In addition to the & and * operators, there are only
four other operators that may be applied to pointer
variables: the arithmetic operators +, ++, - and --.
 Further, you may add or subtract only integer
quantities. You cannot, for example, add a floating
point number to a pointer.
Jane Kuria Inoorero University 07/05/24
Pointer arithmetic
18

 Pointer incrementation arithmetic differs from normal because it is


performed relative to the base type of the pointer.

 Each time a pointer is incremented, it will point to the next item, as


defined by the base type, beyond the one being currently pointed to.

 For example, assume an integer pointer called p contains the address 200.
After the statement p++ executes, p will have the value 202, assuming
integers are 2 bytes long. If p had been a floating point value (4 bytes
long), then the resultant value contained in p would be 204.

 Pointer arithmetic with character appears normal when character pointers


are used. Because characters are 1 byte long, an increment increases the
pointer value by one, decrement decreases it by one.

Jane Kuria Inoorero University 07/05/24


Addition and subtraction of pointers
19

 You may add or subtract any integer quantity you


want, to or from a pointer. For example, the following
is a valid fragment.

 int *p;
 .
 .
 p = p + 200;

 causes p to point to the 200th integer past the one to


which p was currently pointing to.
Jane Kuria Inoorero University 07/05/24
Note
20

 You may not perform any other type of arithmetic


operations. You may not divide, multiply or take modulus
of a pointer.
 However, you may subtract a pointer from another to find
the number of elements separating them.

 Incrementation and decrementation of pointers

 You can apply the increment and decrement operations to


either the pointer itself or the object to which it points.
 However you must be careful when attempting to
increment the object pointed to by a pointer.

Jane Kuria Inoorero University 07/05/24


Note
21

 For example, assume p points to an integer that


contains the value 1.Now consider the statements:

 *p++; and
 *(p)++;

 *p++ first increments p and then obtains the value


at the new location. To increment what is pointed
to by a pointer, you must use the second statement.

Jane Kuria Inoorero University 07/05/24


Pointer precautions
22

 Never use a pointer of one type to point to an object of


a different type.

 For example:
1. int q;
2. float *fp;
3. fp = &q; / *pointer fp assigned address of an
integer */
4. fp = 100.23; /* address used for assignment */

Jane Kuria Inoorero University 07/05/24


Pointer precautions
23

 Do not use a pointer before it has been assigned the address


of a variable. May cause program to crash.

 For example:
1. main()
2. {
3. int *p;
4. *p =10; */Incorrect since p is not pointing to anything
*/
5. …
6. }
 The above is meaningless and dangerous.
Jane Kuria Inoorero University 07/05/24
Pointers and arrays
24

 Pointers can be extended for use in arrays. Array elements can be accesses
using pointers. It is possible to create an array of pointers.

 Accessing arrays using pointers


 We can declare an array of characters and a pointer to a character


 For example
 char line[100], *p;

 We may refer to the first two elements of the array line using
 line[0] = ‘a’;
 line[1] = ’b’; and for each assignment, the compliler calculates
the address.

Jane Kuria Inoorero University 07/05/24


Pointers and arrays
25

 Another way to perform the assignments is to use a


pointer. First, we must initialize the pointer p to point
to the beginning of the array.
 i.e. p = &line [0];

 Since an array’s name is a synonynm to the array’s


starting addres, we can use:
 p = line;

 We can now perform the assignments:


 *p = ‘a’; and *(p+1) = ‘b’;
Jane Kuria Inoorero University 07/05/24
Example: Array manipulation using
26
pointers
1. #include<stdio.h>
2. main()
3. {
4. static int x[3] = {10, 20, 30};
5. int *p1, *p2;
6. p1 = x; /* assign address to a pointer */
7. p2 = & x [2]; /* assign p2 to address of x[2] */
8. printf (“ p1 = %u, *p1 = %d, &p1 = %u \n”, p1, *p1,
&p1);
9. return 0;
10. }

Jane Kuria Inoorero University 07/05/24


Output
27

Jane Kuria Inoorero University 07/05/24


Pointers, arrays and strings
28

An array is in reality a pointer:


 int a[10], y;

 int* px;

 px = a; /* px points to a[0] */

 px++; /* px points to a[1] */

 px=&a[4]; /*px points to a[4] */

 y = *(px+3) /*y gets the value*/

 /* in a[3] */

Jane Kuria Inoorero University 07/05/24


Explanation
29

 The pointer arithmetic in C guarantees that if a


pointer is incremented or decremented, the pointer
will vary according to its type.

 For instance, if px points to an array, px++ will


always yield the next element independently of
what is the type stored in the array

Jane Kuria Inoorero University 07/05/24


Creating pointer arrays
30

 Pointers may be arrayed like any other data type. For example the following
statement declares an integer pointer array that has 20 elements.

 int *pa[20];

 The address of an integer variable myvar is assigned to the ninth element of the
array as follows;

 pa[8]= &myvar;

 Because pa is an array of pointers, the only value that the array elements may hold
are addresses of integer variables. To assign the integer pointed to by the third
element of pa the value 50, use the statement;

 *pa[2] = 50;

Jane Kuria Inoorero University 07/05/24


String variables as pointers
31

 In C a string variable is defined to be simply a pointer


to the beginning of a string.
 char* message;
 message = .This is a string.;

 message is a pointer that now points to the first


character in the string .This is a string.
 Again, use the string.h for string manipulation rather
than doing it directly (you will avoid many errors)
 Take a look this example to understand the relationship
between pointers and strings.

Jane Kuria Inoorero University 07/05/24


Example
32

1. #include<stdio.h>
2. void main( )
3. {
4. char strg[40],*there,one,two;
5. strcpy(strg,"This is a character string.");
6. one = strg[0]; /* one and two are identical */
7. two = *strg;
8. printf("The first output is %c %c\n", one, two);
9. one = strg[8]; /* one and two are indentical */
10. two = *(strg+8);
11. printf("the second output is %c %c\n", one, two);
12. there = strg+10; /* strg+10 is identical to strg[10] */
13. printf("The third output is %c\n", strg[10]);
14. printf("The fourth output is %c\n", *there);
15. }

Jane Kuria Inoorero University 07/05/24


Explanation
33

 You will notice that first we assign a string constant to the string variable
named strg so we will have some data to work with.

 Next, we assign the value of the first element to the variable one, a simple
char variable.

 Since the string name is a pointer by definition, we can assign the same
value to two by using the asterisk and the string name.

 The result of the two assignments are such that one now has the same
value as two, and both contain the character ‘T’, the first character in the
string.

 Note that it would be incorrect to write the ninth line as two = *strg[0];
because the asterisk takes the place of the square brackets.

Jane Kuria Inoorero University 07/05/24


Explanation…
34

 For all practical purposes, strg is a pointer. It does,


however, have one restriction that a true pointer does
not have. It cannot be changed like a variable, but must
always contain the initial value and therefore always
points to its string.
 It could be thought of as a pointer constant, and in
some applications you may desire a pointer that cannot
be corrupted in any way.
 Even though it cannot be changed, it can be used to
refer to other values than the one it is defined to point
to, as we see in the next section of the program.
Jane Kuria Inoorero University 07/05/24
Explanation…
35

 Moving ahead to line 9, the variable one is


assigned the value of the ninth variable (since the
indexing starts at zero) and two is assigned the
same value because we are allowed to index a
pointer to get to values farther ahead in the string.
 Both variables now contain the character ‘a’.

Jane Kuria Inoorero University 07/05/24


Output
36

Jane Kuria Inoorero University 07/05/24


Trouble with pointers
37

 What is printed by the following code?

1. #include <stdio.h>
2. void f(int *aa, int *bb) {
3. *bb = 8;
4. aa[1] = bb[2];
5. aa = bb;
6. }
7. main() {
8. int a[5] = { 1, 2, 3, 4, 5 }, *b;
9. b = a + 2;
10. f(a,b);
11. printf("%d %d %d %d %d\n",
12. a[0], a[1], a[2], a[3], a[4]);
13. }

Jane Kuria Inoorero University 07/05/24


Trouble with pointers
38

 What is printed by the following code?

1. #include <stdio.h>
2. void g(int *aa, int *bb) {
3. bb[2] = aa[-2];
4. *aa++ = 17;
5. *++aa = 10;
6. }
7. main() {
8. int blap[7] = { 1, 2, 3, 4, 5, 6, 7 };
9. int *c = blap + 3;
10. g(c,blap);
11. printf("%d %d %d %d %d %d %d\n",
12. blap[0], blap[1], blap[2], blap[3],
13. blap[4], blap[5], blap[6]);
14. }

Jane Kuria Inoorero University 07/05/24


Revision
39

 Revision Exercise

 1. What is a pointer?

 How do arrays and pointers relate to each other?


 How does pointer arithmetic differ from ordinary arithmetic?


 State two rules one should observe when using pointers.


 Using examples, give the meaning of the pointer operators & and *.

 Write a program that uses a for loop to print digits from 1 to 5 using pointers

Jane Kuria Inoorero University 07/05/24

You might also like