1 chapter 5 pointer. 2 pointers basic concept of pointers pointer declaration pointer operator...

33
1 CHAPTER 5 POINTER

Upload: russell-lang

Post on 04-Jan-2016

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

1

CHAPTER 5

POINTER

Page 2: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

2

Pointers

Basic concept of pointers Pointer declaration Pointer operator (& and *) Parameter passing by reference Dynamic variables

Page 3: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

3

Basic Concept of Pointers In previous chapter, you have learnt about how a function

could return a single value under its name (passed by value).

But, for a function that must return multiple values we use parameter passing by pointers. (It is so called as passed by reference).

A pointer is a variable which directly points to a memory address.

It will allow the programmer to directly manipulate the data in memory.

So far, we have seen that a variable is used to store a value. A pointer variable, however, does not store a value but instead store the address of the memory space which contain the value.

Page 4: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

4

Why would we want to use pointers? To call a function by reference so that the data

passed to the function can be changed inside the function.

To create a dynamic data structure which can grow larger or smaller as necessary.

Basic Concept of Pointers

Page 5: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

5

A variable declaration such as, int number = 20; causes the compiler to allocate a

memory location for the variable number and store in it the integer value 20.

This absolute address of the memory location is readily available to our program during the run time.

The computer uses this address to access its content.

number

20number directly references a variable whose value is 20

Basic Concept of Pointers cont…

Page 6: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

6

A pointer declaration such as, int *numberptr, number = 20; declares numberptr as

a variable that points to an integer variable. Its content is not integer value 20 but, it is a memory address.

The * indicates that the variable being defined is a pointer.

In this sense, a variable named directly references a value, however a pointer indirectly references a value.

number

20numberptr indirectly references a variable whose value is 20

numberptr

Basic Concept of Pointers Cont…

Page 7: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

7

Memory contentMemory address

0x00000x00010x00020x0003… ...

......

0xFFFF0xFFFE0xFFFD0xFFFC

27107699

0x0002787878999

A variable of type int isstored here. The address of this location is 0x0002.

This location contains thevalue 0x0002. Therefore thislocation stores a pointer variable which points to the address 0x0002.

Graphical Representation of MM

Page 8: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

8

Pointer Declaration

General format:data_type *ptr_name;

Example: Pointer to an int: int *intptr; Pointer to a char: char *charptr;

The asterisk (*) character in front of the variable name tells that the variable is a pointer and not a variable to store value.

Page 9: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

Pointer Declaration (con’t) Consider the statements:

#include <stdio.h> int main ( ) { FILE *fptr1 , *fptr2 ; /* Declare two file pointers */ int *aptr ; /* Declare a pointer to an int */ float *bptr ; /* Declare a pointer to a float */ int a ; /* Declare an int variable */ float b ; /* Declare a float variable */

Page 10: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

10

Pointer Operator (& and *) To prevent the pointer from pointing to a

random memory address, it is advisable that the pointer is initialized to 0 or NULL before being used.

When a pointer is created, it is not pointing to any valid memory address. Therefore, we need to assign it to a variable’s address by using the & operator. This operator is called a reference operator.

After a pointer is assigned to a particular address, the value in the pointed address can be accessed using the * operator. This operator is called a dereference operator.

Page 11: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

11

Pointer Operator (& and *) Look at this example:

int num = 9;int *num_ptr;num_ptr = &num;printf(“num = %d”, *num_ptr);

Output: num = 9

Page 12: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

int *num_ptr, num = 9;

num_ptr = &num;

91100110011111111

num*num_ptr

9110011001100110011111111

num*num_ptr

Graphical representation of a pointer pointing to an integer variable in memory

Representation of num and numPtr in memory

Pointer Operator (& and *) Cont…

Page 13: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

13

#include <stdio.h>void main(void) { int var = 10; int *ptrvar = &var;

printf(“The address of the variable var is: %x\n”, &var); printf(“The value of the pointer ptrvar is: %x\n”, ptrvar); printf(“Both values are the same\n”);

printf(“The value of the variable var is: %d\n”, var); printf(“The value of *ptrvar is: %d\n”, *ptrvar); printf(“Both values are the same\n”); printf(“The address of the value pointed by ptrvar is: %d\n”, &*ptrvar); printf(“The value inside the address of ptrvar is: %d\n”, *&ptrvar); printf(“Both values are the same\n”);}

Example

Page 14: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

14

Output/*Sample Output

The address of the variable var is: 1245052The value of the pointer ptrvar is: 1245052Both values are the same

The value of the variable var is: 10The value of *ptrvar is: 10Both values are the same

The address of the value pointed by ptrvar is: 1245052The value inside the address of ptrvar is: 1245052Both values are the same

Press any key to continue*/

Page 15: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

Exercise 1 (5 minutes) Draw a picture of memory after these

statements: int i = 42; int k = 80; int* p1; int* p2; p1 = &i; p2 = &k;

Page 16: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

16

Parameter Passing by Reference A function call by reference can be done by

passing a pointer to the function argument (the same way as passing a normal variable to the argument).

When the value referenced by the pointer is changed inside the function, the value in the actual variable will also change.

Therefore, we can pass the result of the function through the function argument without having to use the return statement. In fact, by passing pointers to the function argument, we can return more than one value.

Page 17: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

17

When a pointer is passed to a function, we are actually passing the address of a variable to the function.

Since we have the address, we can directly manipulate the data in the address.

In the case where a non-pointer variable is passed, the function will create another space in memory to hold the value locally while the program is inside the function. Therefore, any change to the variable inside the function will not change the actual value of the variable.

Parameter Passing by Reference Cont…

Page 18: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

18

To pass the value of variable by pointers between two functions, we must do the following:

1. Declare the variable that is meant to return a value to the calling function as a pointer variable in the formal parameter list of the function.

void called_function(int *result);

2. When to call the function, use a variable together with address operator (&)

called_function(&value_returned);

Parameter Passing by Reference Cont…

Page 19: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

19

Note : the effect of the above two actions is the same as the effect of the declarations int value_returned; int *result=&value_returned;

3. Declare the function with pointer parameter appropriately in a function prototype by using symbol * as a prefix for pointer parameters.

void called_function(int *x);

Parameter Passing by Reference Cont…

Page 20: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

20

void Func1(int a, int b) { a = 0; b = 0; printf(“Inside Func1, a = %d, b = %d\n”, a, b);}

#include <stdio.h>void Func1(int, int);void Func2(int *, int *);

void main(void) { int a = 8, b = 9; printf(“Before Func1 is called, a = %d, b = %d\n”, a, b); Func1(a, b); printf(“After Func1 is called, a = %d, b = %d\n”, a, b);

printf(“\nBefore Func2 is called, a = %d, b = %d\n”, a, b); Func2(&a, &b); printf(“After Func2 is called, a = %d, b = %\nd”, a, b);}

Example

Page 21: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

21

Output:Before Func1 is called, a = 8, b = 9Inside Func1, a = 0, b = 0After Func1 is called, a = 8, b = 9

Before Func2 is called, a = 8, b = 9Inside Func2, *pa = 0, *pb = 0After Func2 is called, a = 0, b = 0

void Func2(int *pa, int *pb) { *pa = 0; *pb = 0; printf(“Inside Func2, *pa = %d, *pb = %d\n”, *pa, *pb);}

Example Cont…

Page 22: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

22

Dynamic Variables Variables that can be created and destroyed

during program execution. To use dynamic variables:

Decide the type of data to be stored in such variable Declare a pointer variable of that data type Assign to the pointer the address created by the

standard library function malloc.(malloc is declared in the standard header file stdlib.h)

Page 23: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

Dynamic Variables (con’t) The function malloc is used to allocate a certain

amount of memory during the execution of a program.

The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory.

When the amount of memory is not needed anymore, we must return it to the operating system by calling the function free.

23

Page 24: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

Dynamic Variables (con’t) Usage of malloc():

void * malloc ( size_t size ); Parameters:

Size of the memory block in bytes. Return value:

If the request is successful then a pointer to the memory block is returned.

If the function failed to allocate the requested block of memory, a NULL pointer is returned.

24

Page 25: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

Source code example of malloc()#include<stdio.h> #include<stdlib.h> int main () { int * buffer; buffer = (int*) malloc (10*sizeof(int)); if (buffer==NULL) { printf("Error allocating memory!"); exit (1); } free (buffer); return 0; }

25

Page 26: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

26

Dynamic Variables (Con’t)#include<stdio.h>

int main()

{

int *ptr_one;

ptr_one = (int *) malloc(sizeof(int)); /* The malloc statement will ask for an amount of memory with the size of an integer (32 bits or 4 bytes). If there is

not enough memory available, the malloc function will return a NULL. If the request is granted a block of memory is allocated (reserved). The address of the reserved block will be placed into the pointer variable, ptr_one*/

if (ptr_one == 0) /*The if statement then checks for the return value of NULL. If the return value equals NULL, then a message will be

printed and the programs stops. If the return value of the program equals one, than that’s an indication to proceed to the next statements*/

{

printf("ERROR: Out of memory\n");

return 1;

} /*The number twenty-five is placed in the allocated memory. Then the value in the allocated memory will be printed.

Before the program ends the reserved memory is released. free(ptr_one) causes the OS to release the memory location pointed by the pointer variable ptr_one.*/

*ptr_one = 25;

printf("%d\n", *ptr_one);

free(ptr_one);

return 0;

}

Page 27: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

27

Dynamic Variables (Con’t)int *ptr;

ptr = malloc(sizeof(int));

*ptr = 5;

free(ptr);

ptr=NULL;

?ptr

ptr ?

ptr 5

ptr Invalid address

ptr NULL

Page 28: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

Dynamic Variables Cont…

sizeof This keyword can be used to determine the number of bytes in

a data type, a variable, or an array Example: double array [10]; sizeof (double); /* Returns the value 8 */ sizeof (array); /* Returns the value 80 */ sizeof(array)/sizeof(double); /* Returns 10 */

Page 29: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

29

Dynamic Variables Cont… Normally we use the sizeof operator on a data type to

specify the number of bytes as the argument of malloc. In previous example, malloc instructs the OS to allocate a

memory location of sizeof(int) bytes. If there is enough space in the free store, the OS gives it

to the program and makes its address available to malloc i.e malloc returns the address of the dynamically allocated memory location to the pointer variable ptr_one.

If there is no available space, malloc returns NULL.

Page 30: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

Sizeof() : Example/* * $Id: sizeof.c,v 1.1 2009/07/05 10:37:54 sms Exp $ * www.pccl.demon.co.uk * *

Program to display data sizes. */ #include <stdio.h> #include <time.h> #include <sys/types.h> #define printsize(x) printf ("sizeof (" #x ") = %d\n", sizeof (x)) main () { printf ("\nC\n"); printsize (char); printsize (double); printsize (float); printsize (int); printsize (long); printsize (long long); printsize (short); printsize (void *); }

30

Page 31: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

Sizeof() : Example (con’t)sizeof (char) = 1 sizeof (double) = 8 sizeof (float) = 4 sizeof (int) = 4 sizeof (long) = 4 sizeof (long long) = 8 sizeof (short) = 2 sizeof (void *) = 4

31

Page 32: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

Functions used in Memory ManagementFunction Task

malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space

calloc Allocates space for an array of elements initializes them to zero and returns a pointer to the memory

free Frees previously allocated space

realloc Modifies the size of previously allocated space

32

Page 33: 1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic

33

SUMMARY This chapter has exposed you about: Pointer variables and parameter passing

by reference/ pointers The usange of symbol * and address

operator (&) Passing by pointers allows us to return

multiple values from functions How to use dynamic variables