Sunteți pe pagina 1din 41

Pointers

Roadmap

Overview What is C? > C Features > Memory layout > Working with Pointers
>

2.2

What is C?

C was designed as a general-purpose language with a very direct mapping from data types and operators to machine instructions. > cpp (C pre-processor) used for expanding macros and inclusion of declaration header files > explicit memory allocation (no garbage collection) > memory manipulation through pointers, pointer arithmetic and typecasting > used as portable, high-level assembler

2.3

C Features

Developed in 1972 by Dennis Ritchie and Brian Kernighan as a systems language for Unix on the PDP-11. A successor to B [Thompson, 1970], in turn derived from BCPL.
C preprocessor: Data types: Type constructors: Basic operators: Control abstractions: Functions: Type operations: file inclusion, conditional compilation, macros char, short, int, long, double, float pointer, array, struct, union arithmetic, pointer manipulation, bit manipulation ... if/else, while/for loops, switch, goto ... call-by-value, side-effects through pointers typedef, sizeof, explicit type-casting and coercion

2.4

C Storage Classes

You must explicitly manage storage space for data Static Automatic Dynamic static objects exist for the entire life-time of the process automatic objects only live during function invocation on the run-time stack dynamic objects live between calls to malloc and free their lifetimes typically extend beyond their scope

2.5

Memory Layout
The address space consists of (at least): Text: Static: Heap: Stack: executable program text (not writable) static data dynamically allocated global memory (grows upward) local memory for function calls (grows downward)

2.6

Where is memory?
#include <stdio.h> Static is here: 8216 static int stat=0; Heap is here: 279216 void dummy() { } Stack is here: int main(void) 3221223448 { int local=1; int *dynamic = (int*) malloc(sizeof(int)); printf("Text is here: %u\n", (unsigned) dummy); /* function pointer */ printf("Static is here: %u\n", (unsigned) &stat); printf("Heap is here: %u\n", (unsigned) dynamic); printf("Stack is here: %u\n", (unsigned) &local); }
2.7

Text is here: 7604

Roadmap

> > > > >

Basics of Pointers Why Pointers? Initialization Function pointers Typecasting

2.8

Pointer Basics

> > > > > > >

What is a pointer ? What is a variable ? Something with a name, the value of which can vary.
int k; k=12;

When we declare a variable, we inform the compiler of two things, the name of the variable and the type of the variable. lvalue & rvalue ? An object is a named region of storage; an lvalue is an expression referring to such an object. The term rvalue refers to a data value that is stored at some address in memory.

Cont.
2.9

Pointer Basics

>

Consider an example:
int j, k; k = 2; j = 7; <-- line 1 k = j; <-- line 2

> > > >

Here, the compiler interprets the j in line 1 as address of the variable j (its lvalue) and creates code to copy the value 7 to that address. In line 2, however, j is interpreted as its rvalue (since it is on the right hand side of the assignment operator '='). That is, here the j refers to the value stored at the memory location set aside for j, in this case 7. So, the 7 is copied to the address designated by the lvalue of k.

Cont.
2.10

Pointer Basics

> > > > > >

Now, let's say that we have a reason for wanting a variable designed to hold an lvalue (an address). The size required to hold such a value depends on the system. Computers with more memory would require more bytes to hold an address. Such a variable is called a pointer variable. In C a pointer variable is defined by preceding its name with an asterisk. Also, pointer has to be given a type which, in this case, refers to the type of data that will be stored at the address stored in the pointer.
int *ptr;

Cont.
2.11

Why pointers?

> > > >

With arrays: Extravagant waste of space. Strange to declare a 500 million character array to look at 100 lines of code. Have to declare it to have its maximum size in every dimension from the beginning, while there is no way to predict and handle the maximum line length of a text file, because, technically, that number is infinite.

Cont.
2.12

Why pointers?

> > > > > >

With pointers: You can create dynamic data structures. Allocation of memory from the heap while the program is running. Ability to use the exact amount of memory a document needs, with no waste. Ability to return the memory to the heap when you close a document. Memory can be recycled while the program is running.

2.13

Initialization of Pointers

>

Can be initialized four different ways.


1. 2. 3. 4. Using malloc statement Using statement such as p = q . If q is pointing at a valid block, p is initialized. Pointing to a known address, such as a global variable's address. Ex.
p=&i

Using value zero i.e., p = 0; or: p = NULL;

2.14

POINTERS- & AND * OPERATORS

> > >

Consider the declaration, Int i=3; Declaration tells the compiler:


 Reserve space in memory to hold the integer value.  Associate the name i with this memory location.  Store the value 3 at this location. i 3 6485 Location name Value at location Location no. (address)

2.15

POINTERS

Computer has selected 6485 as the place to store the value 3. > Location number may vary when you compile the program different time on different machine. > Important point is, is address in memory is a number.
>

2.16

POINTERS Example

main() { Int I=3; Printf( \n address of I =%u, &i); Printf( \n value of I =%u, i); }
>

Output would be:


Address of I=6485 Value of I=3;

In the first printf, &- address of operator Other pointer available in C is *,called value at address or indirection operator.

2.17

POINTERS Example

main() { Int I=3; Printf( \n address of I =%u, &i); Printf( \n value of I =%u, i); printf( \n value of i=%d,*(&i)); } Output:
address of I=6485 value of I=3 value of I=3

*(&i)- prints the value of i.

2.18

POINTER Expressions

> > > > > >

We have seen that, &I returns the address of i. This address can be collected in a variable by saying, J=&I But, J is not an ordinary integer variable It is the variable which contains the address of the other variable. Compiler provides space in the memory for the variable j as shown here:

2.19

POINTERS

I 3 6485

J 6485 3276

J must be declared before used in the program. It is declared as, Int *j;

2.20

POINTERS

main() { Int i=3; Int *j; J=&I; Printf(\n address of i=%u, &i); Printf(\n address of i=%u, j); Printf(\n address of j=%u, &j); Printf(\n value of j=%d, j); Printf(\n value of i=%d, i); Printf(\n value of i=%d, *(&i)); Printf(\n value of i=%d, *j); }

Good understanding of expressions &I, &j, *j and *(&i) is important to get a good grip on pointers.
2.21

POINTERS-Example

>

Output of the above program:


Address of i=6485 Address of j=6485 Address of j=3276 Value of j=6485 Value of i=3 Value of i=3 Value of i=3

2.22

POINTERS

>

Look at the following declarations,


Int *alpha; Char *ch; Float *s;

Here alpha, ch and s are declared as pointer variables (holding addresses). > S-going to have the address of a floating point value > Ch-going to have a address of char value.
>

2.23

POINTERS Example

Main() { Int i=3; Int *j; Int **k; J=&I; K=&j; Printf(\n address of i=%u, &i); Printf(\n address of i=%u, j); Printf(\n address of i=%u,*k); Printf(\n address of j=%u ,&j); Printf(\n address of j=%u ,k); Printf(\n address of k=%u, &k);

Continued..
2.24

POINTERS
Printf( \n \n value of j = %u, j); Printf(\n value of k=%u, k); Printf(\n value of i=%d, i); Printf(\n value of i=%d,*(&i)); Printf(\n value of i=%d,*j); Printf(\n value of i=%d,**k); }

i 3 6485

j 6485 3276

k 3276 7234

2.25

POINTERS

>

Output of the program would be:


Address of i=6485 Address of i=6485 Address of i=6485 Address of j=3276 Address of j=3276 Address of k=7234 Value of j=6485 Value of k=3276 Value of i=3 Value of i=3 Value of i=3 Value of i=3

2.26

POINTERS-Char, Int and float pointers

> > > > > > > > > > > > > > >

Main() { Char c,*cc; Int I,*ii; Float a,*aa; c=A; i=54; a=3.14; cc=&c; ii=&I; aa=&a; Printf( \n address contained in cc=%u \t and value of c=%c \n, cc,*cc); Printf( \n address contained in ii=%u \t and value of i=%d \n, ii,*ii); Printf( \n address contained in aa=%u \t and value of a=%f \n, aa,*aa); }

2.27

POINTERS

>
> > >

Output of the program would be:


address contained in cc=1004 address contained in ii=2008 address contained in aa=7006 and value of c=A and value of i=54 and value of c=3.140000

c 65 cc 1004

i Binary eq of 54 ii 2008

a Binary equivalent of 3.14 aa 7006

2.28

Function Pointers
> function itself is not a

variable,but it is possible to define pointers to functions which can be assigned, placed in arrays, passed to functions,returned from functions and so on..

Passing Addresses to functions

Addresses of actual arguments in the calling function are copied into formal arguments of the called function. > Changes made in the formal arguments reflects on the actual arguments. > Following program illustrates this fact:
>

2.30

Pass by address-example
main( ) { int a = 10, b = 20 ; swapr ( &a, &b ) ; printf ( "\n a = %d b = %d", a, b ) ; } swapr( int *x, int *y ) { int t ; t = *x ; *x = *y ; *y = t ; }

Output would be: a=20 b=10


2.31

Pass by address

> >

By using pass by address intelligently, we can make a function return more than one value at a time. Example:
main( ) { int radius ; float area, perimeter ; printf ( "\n Enter radius of a circle " ) ; scanf ( "%d", &radius ) ; areaperi ( radius, &area, &perimeter ) ; printf ( "Area = %f", area ) ; printf ( "\n Perimeter = %f", perimeter ) ; } areaperi ( int r, float *a, float *p ) { *a = 3.14 * r * r ; *p = 2 * 3.14 * r ; }

2.32

Pass by address

Passing the value of radius but,addresses of area and perimeter. > Any change we make to the values stored at addresses contained in the variables,would make change effective even in main()
>

2.33

Functions returning pointers

Function can even return a pointer,like it return int,float,a double or another data type. > To make a function return a pointer,it has to be explicitly mentioned in the calling function as well as in the function definition.
>

2.34

Functions returning pointers

/*Example*/

#include<stdio.h> main() { int *p; int *fun(); p=fun(); printf("\n%u\n",p); printf("\n%d\n",*p); printf("\n%u\n",&i); } int *fun() { static int i=20; return (&i); }

2.35

Typecasting

To convert one type of variable to other type. > General form: (type) expression > Operation tell c to compute the value of the expression, and then convert it to specific type. > This is useful when you work with integers and floating point numbers.
>

2.36

Typecasting

int won, lost; /* # games won/lost so far */ float ratio; /* win/lose ratio */ won = 5; lost = 3; ratio = won / lost; /* ratio will get 1.0 (a wrong value) */ /* The following will compute the correct ratio */ ratio = ((float) won) / ((float) lost); It is also used to convert pointers of one type to other.

2.37

Roadmap

>

Summary

2.38

Pointers
A pointer holds the address of an object
int i = 10; int *ip = &i; /* assign address of i to ip */ *ip = *ip + 1; int *ep = eightPrimes; ep[7] = 23; sizeof(eightPrimes) == 32) sizeof(ep) == 4) ep = ep+1; void *vp = ep; ((int*)vp)[6] = 29;

Use them to access and update variables: Array variables behave like pointers to their first element Pointers can be treated like arrays: But have different sizes: You may increment and decrement pointers: Declare a pointer to an unknown data type as void* But typecast it properly before using it!

2.39

> > > > >

I request Electronics and communication ENGINEERING students to visit my blog for more

abhishek1ek.blogspot.com > awhengineering.blogspot.com

2.40

2.41

S-ar putea să vă placă și