36
LECTURE - 10 POINTER PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET. 1

LECTURE-10 POINTER

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Page 1: LECTURE-10 POINTER

LECTURE-10POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

1

Page 2: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

2

POINTERS:Pointers in C are easy and fun to learn. Some Cprogramming tasks are performed more easilywith pointers, and other tasks, such asdynamic memory allocation, cannot beperformed without using pointers. So itbecomes necessary to learn pointers tobecome a perfect C programmer. Let's startlearning them in simple and easy steps.

Page 3: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

3

As you know, every variable is a memory location andevery memory location has its address defined whichcan be accessed using ampersand (&) operator, whichdenotes an address in memory. Consider thefollowing example, which prints the address of thevariables defined:int main (){int var1;char var2[10];printf("Address of var1 variable: %x\n", &var1 );printf("Address of var2 variable: %x\n", &var2 );return 0; }

Page 4: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

4

When the above code is compiled and executed, itproduces the following result:Address of var1 variable: bff5a400Address of var2 variable: bff5a3f6The most crucial of all of C’s grammars is pointers.Many other programming languages have thesimilar concept as pointer in C, but they merely donot use the best of pointers. C uses pointers as itsinevitable part. Though the understanding ofpointers is the most difficult part in learning C, onceyou have the clean idea on pointers, you will seethat by using pointers, you can solve any problem inC.

Page 5: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

5

Consider the declaration-int i = 3;This declaration tells the C compiler to:(a) Reserve space in memory to hold the integervalue.(b) Associate the name i with this memory location.(c) Store the value 3 at this location.

Page 6: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

6

• We see that the computer has selectedmemory location 65524 as the place to storethe value 3. The location number 65524 is not anumber to be relied upon, because some othertime the computer may choose a differentlocation for storing the value 3. The importantpoint is, i’s address in memory is a number. Wecan print this address number through thefollowing program:

Page 7: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

7

The output of the above program would be:

Page 8: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

8

• Look at the first printf( ) statement carefully. ‘&’used in this statement is C’s ‘address of’ operator.The expression &i returns the address of thevariable i, which in this case happens to be 65524.Since 65524 represents an address, there is noquestion of a sign being associated with it. Hence itis printed out using %u, which is a format specifierfor printing an unsigned integer. We have beenusing the ‘&’ operator all the time in the scanf( )statement.

Page 9: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

9

The other pointer operator available in C is ‘*’, called‘value at address’ operator. It gives the value stored ata particular address. The ‘value at address’ operator isalso called ‘indirection’ operator.• Observe carefully the the following program:

Page 10: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

10

The expression &i gives the address of the variable i.This address can be collected in a variable, by saying,j = &i ;But remember that j is not an ordinary variable likeany other integer variable. It is a variable thatcontains the address of other variable (i in this case).Since j is a variable the compiler must provide itspace in the memory. Once again, the followingmemory map would illustrate the contents of i and j.

Page 11: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

11

As you can see, i’s value is 3 and j’s value is i’s address.But wait, we can’t use j in a program withoutdeclaring it. And since j is a variable that contains theaddress of i, it is declared as, int *j ;This declaration tells the compiler that j will be usedto store the address of an integer value. In otherwords j points to an integer. How do we justify theusage of * in the declaration, int *j ;

Page 12: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

12

Let us go by the meaning of *. It stands for ‘value ataddress’. Thus, int *j would mean, the value at theaddress contained in j is an intHere is a program that demonstrates the relationshipswe have been discussing.

Page 13: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

13

The output of the above program would be:

Look at the following declarations,int *alpha ; char *ch ; float *s ;

Page 14: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

14

• Here, alpha, ch and s are declared as pointervariables, i.e. variables capable of holdingaddresses. Remember that, addresses (locationnos.) are always going to be whole numbers,therefore pointers always contain wholenumbers. Now we can put these two factstogether and say—pointers are variables thatcontain addresses, and since addresses are alwayswhole numbers, pointers would always containwhole numbers.

Page 15: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

15

• The declaration float *s does not mean that s isgoing to contain a floating-point value. What itmeans is, s is going to contain the address of afloating-point value. Similarly, char *ch means thatch is going to contain the address of a char value.Or in other words, the value at address stored in chis going to be a char.

Page 16: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

16

• The concept of pointers can be further extended.Pointer, we know is a variable that containsaddress of another variable. Now this variableitself might be another pointer. Thus, we nowhave a pointer that contains another pointer’saddress. The following example should make thispoint clear.

Page 17: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

17

Page 18: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

18

The output of the above program would be:

Page 19: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

19

• Remember that when you run this program theaddresses that get printed might turn out to besomething different than the ones shown in thefigure. However, with these addresses too therelationship between i, j and k can be easilyestablished.

Page 20: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

20

Observe how the variables j and k have beendeclared,

int i, *j, **k ;Here, i is an ordinary int, j is a pointer to an int(often called an integer pointer), whereas k is apointer to an integer pointer. We can extend theabove program still further by creating a pointer toa pointer to an integer pointer.

Page 21: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

21

What are Pointers?A pointer is a variable whose value is the address ofanother variable, i.e., direct address of the memorylocation. Like any variable or constant, you mustdeclare a pointer before using it to store any variableaddress. The general form of a pointer variabledeclaration is:

type *var-name;Here, type is the pointer's base type; it must be avalid C data type and varname is the name of thepointer variable.

Page 22: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

22

Take a look at some of the valid pointer declarations:

int *ip; /* pointer to an integer */double *dp; /* pointer to a double */float *fp; /* pointer to a float */char *ch /* pointer to a character */The actual data type of the value of all pointers,whether integer, float, character, or otherwise, is thesame, a long hexadecimal number that represents amemory address. The only difference betweenpointers of different data types is the data type of thevariable or constant that the pointer points to.

Page 23: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

23

A pointer is a variable that contains the address of avariable. Consider the following statement:

int quantity = 179;This statement instructs the system to find a locationfor the integer variable quantity and puts the value179 in that location. Let, the system has chosen theaddress location 5000 for quantity. During theexecution of the program, the system alwaysassociates the name quantity with the address 5000.

Page 24: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

24

• We may have access to the value 179 by usingeither the name quantity or the address 5000.Since the memory addresses are simply thenumbers, they can be assigned to somevariables that can be stored in the memory likeany other variable. Such variables that holdmemory addresses are called pointer variables.

Page 25: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

25

Suppose, we assign the address of quantity to avariable p. Since the value of the variable p is theaddress of the variable quantity, we may access thevalue of the quantity by using the value of p andtherefore, we say that the variable p points to thevariable quantity. Thus p gets the name pointer.

Page 26: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

26

Accessing the Address of a VariableThe address of a variable can be determined by using& (address operator) operator. For example, thestatementp = &quantity ;would assign the address 5000 (the location ofquantity) to the variable p.Declaring Pointer VariablesSyntax:data_type *pointer_name;

Page 27: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

27

This tells the compiler three things:The asterisk (*) tells the variable pointer_name is apointer variable.pointer_name needs a memory location.pointer_name points to a variable of typedata_type.Once a pointer variable has been declared we canuse the assignment operator to initialize thevariable. For example,

int quantity;int *p;p = &quantity

Page 28: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

28

Accessing a Variable through its PointerThis is done by using unary operator (*), also knownas indirection operator. For example,int quantity, *p, n;quantity = 179;p = &quantity;n = *p;here, the value of n will be 179.

Page 29: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

29

Chain of PointerIt is possible to make a pointer to point to anotherpointer, thus creating a chain of pointers as shown:This is known as multiple indirections.

Page 30: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

30

Pointer ExpressionLike other variables, pointer variables can be used inexpressions. For example,

y= *p1 * *p2;Note:Only an address of a variable can be stored in apointer variable. Do not store the address of avariable of one type into a pointer variable of anothertype. The value of a variable can’t be assigned to apointer variable. A pointer variable contains garbageuntil it is initialized.

Page 31: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

31

How to Use Pointers?There are a few important operations, whichwe will do with the help of pointers veryfrequently.(a)We define a pointer variable,(b) assign the address of a variable to apointer, and(c) finally access the value at the addressavailable in the pointer variable.

Page 32: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

32

NULL Pointers:It is always a good practice to assign a NULL value to apointer variable in case you do not have an exactaddress to be assigned. This is done at the time ofvariable declaration. A pointer that is assigned NULL iscalled a null pointer. The NULL pointer is a constantwith a value of zero defined in several standardlibraries. Consider the following program:int main (){int *ptr = NULL;printf("The value of ptr is : %x\n", ptr );return 0; }

Page 33: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

33

When the above code is compiled and executed, itproduces the following result:

The value of ptr is 0In most of the operating systems, programs are notpermitted to access memory at address 0 becausethat memory is reserved by the operating system.However, the memory address 0 has specialsignificance; it signals that the pointer is not intendedto point to an accessible memory location. But byconvention, if a pointer contains the null (zero) value,it is assumed to point tonothing.

Page 34: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

34

Pointers in DetailPointers have many but easy concepts and they arevery important to C programming.The following important pointer concepts should beclear to any C programmer:

Page 35: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

35

Page 36: LECTURE-10 POINTER

PINGKI DATTA, LECTURER, DEPARTMENT OF CIVIL ENGINEERING, KUET.

36

Thanks to Everyone

SEE YOU IN THE NEXT CLASS.