P10_PointersInC

download P10_PointersInC

of 41

Transcript of P10_PointersInC

  • 8/3/2019 P10_PointersInC

    1/41

    Pointers

  • 8/3/2019 P10_PointersInC

    2/41

    2.2

    Roadmap

    Overview

    > What is C?

    > C Features

    > Memory layout

    > Working with Pointers

  • 8/3/2019 P10_PointersInC

    3/41

    2.3

    What is C?

    C was designed as a general-purpose language with a very directmapping from data types and operators to machine instructions.

    > cpp(C pre-processor) used for expanding macros and inclusion ofdeclaration header files

    > explicit memory allocation (no garbage collection)

    > memory manipulation throughpointers,pointer arithmetic and

    typecasting

    > used asportable, high-level assembler

  • 8/3/2019 P10_PointersInC

    4/41

    2.4

    C Features

    Developed in 1972 by Dennis Ritchie and Brian Kernighan as a systems language forUnix on the PDP-11. A successor to B [Thompson, 1970], in turn derived from BCPL.

    C preprocessor: file inclusion,conditionalcompilation, macrosData types: char, short, int,long, double, float

    Type constructors: pointer, array, struct, union

    Basic operators: arithmetic,pointer manipulation, bit manipulation ...

    Control abstractions: if/else, while/forloops, switch, goto ...

    Functions: call-by-value, side-effects through pointers

    Type operations: typedef, sizeof, explicit type-casting and coercion

  • 8/3/2019 P10_PointersInC

    5/41

    2.5

    C Storage Classes

    You must explicitly manage storage space for data

    Static static objects exist for the entire life-time of theprocess

    Automaticautomatic objects only live during function invocation

    on the run-time stack

    Dynamic dynamic objects live between calls to malloc and free theirlifetimes typically extend beyond their scope

  • 8/3/2019 P10_PointersInC

    6/41

    2.6

    Memory Layout

    The address space consists of(at least):

    Text: executable program text (not writable)

    Static: static data

    Heap: dynamically allocated global memory (grows upward)Stack: local memory for function calls (grows downward)

  • 8/3/2019 P10_PointersInC

    7/41

    2.7

    Where is memory?

    #include

    static int stat=0;

    void dummy() { }

    int main(void)

    {

    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);

    }

    Text is here: 7604

    Static is here: 8216

    Heap is here: 279216

    Stack is here:

    3221223448

  • 8/3/2019 P10_PointersInC

    8/41

    2.8

    Roadmap

    > Basics of Pointers

    > Why Pointers?> Initialization

    > Function pointers

    > Typecasting

  • 8/3/2019 P10_PointersInC

    9/41

    2.9

    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 variableand the type of the variable.

    > lvalue &rvalue ?

    > An objectis 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.

  • 8/3/2019 P10_PointersInC

    10/41

    2.10

    Pointer Basics

    > Consider an example: int j,k;

    k=2;

    j = 7; In line 2, however,jis interpreted as its rvalue (since it is on the right hand side of the assignmentoperator '=').

    > That is, here thejrefers to the value storedat the memory location set aside forj, in this case 7.

    > So, the 7 is copied to the address designated by the lvalue ofk.

    Cont.

  • 8/3/2019 P10_PointersInC

    11/41

    2.11

    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 apointer 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 atthe address stored in the pointer. int *ptr;

    Cont.

  • 8/3/2019 P10_PointersInC

    12/41

    2.12

    > With arrays:

    > Extravagant waste of space.

    > Strange to declare a 500 million character array to look at 100 lines ofcode.

    > Have to declare it to have its maximum size in every dimension from the beginning, whilethere is no way to predict and handle the maximum line length of a text file, because,technically, that number is infinite.

    Why pointers?

    Cont.

  • 8/3/2019 P10_PointersInC

    13/41

    2.13

    > 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.

    Why pointers?

  • 8/3/2019 P10_PointersInC

    14/41

    2.14

    Initialization of Pointers

    > Can be initialized four different ways.

    1. Using malloc statement2. Using statement such as p= q . If q is pointing at a valid block, p is

    initialized.

    3. Pointing to a known address, such as a global variable's address. Ex.p=&i

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

  • 8/3/2019 P10_PointersInC

    15/41

    2.15

    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.

    3

    i

    6485

    Location name

    Value at location

    Location no. (address)

  • 8/3/2019 P10_PointersInC

    16/41

    2.16

    POINTERS

    > Computer has selected 6485 as the place to store the value 3.

    > Location number may vary when you compile the program differenttime on different machine.

    > Important point is, is address in memory is a number.

  • 8/3/2019 P10_PointersInC

    17/41

    2.17

    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

    Otherpointer available in C is *,called value at address or indirection operator.

  • 8/3/2019 P10_PointersInC

    18/41

    2.18

    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.

  • 8/3/2019 P10_PointersInC

    19/41

    2.19

    POINTERExpressions

    > 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.

    > Compilerprovides space in the memory for the variable j as shown here:

  • 8/3/2019 P10_PointersInC

    20/41

    2.20

    POINTERS

    3 6485

    I

    6485

    J

    3276

    J must be declared before used in the program. It is declared as,

    Int *j;

  • 8/3/2019 P10_PointersInC

    21/41

    2.21

    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.

  • 8/3/2019 P10_PointersInC

    22/41

    2.22

    POINTERS-Example

    > Output of the above program:

    Address of i=6485Address of j=6485

    Address of j=3276

    Value of j=6485

    Value of i=3

    Value of i=3

    Value of i=3

  • 8/3/2019 P10_PointersInC

    23/41

    2.23

    POINTERS

    > Look at the following declarations,Int *alpha;

    Char *ch;

    Float *s;

    > Here alpha,ch and s are declared as pointer variables (holdingaddresses).

    > S-going to have the address of a floating point value> Ch-going to have a address ofchar value.

  • 8/3/2019 P10_PointersInC

    24/41

    2.24

    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 ofk=%u,&k);

    Continued..

  • 8/3/2019 P10_PointersInC

    25/41

    2.25

    POINTERS

    Printf( \n \n value of j =%u, j);

    Printf(\n value ofk=%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);}

    3 6485 3276

    i kj

    6485 72343276

  • 8/3/2019 P10_PointersInC

    26/41

    2.26

    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 ofk=7234

    Value of j=6485

    Value ofk=3276

    Value of i=3

    Value of i=3

    Value of i=3

    Value of i=3

  • 8/3/2019 P10_PointersInC

    27/41

    2.27

    POINTERS-Char, Int and float pointers

    > Main()

    > {

    > Charc,*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 ofc=%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);

    > }

  • 8/3/2019 P10_PointersInC

    28/41

    2.28

    POINTERS

    > Output of the program would be:> address contained in cc=1004 and value ofc=A

    > address contained in ii=2008 and value of i=54

    > address contained in aa=7006 and value ofc=3.140000

    65

    1004

    Binary eq of 54

    2008

    Binary equivalent of3.14

    7006

    c i a

    cc ii aa

  • 8/3/2019 P10_PointersInC

    29/41

    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..

  • 8/3/2019 P10_PointersInC

    30/41

    2.30

    Passing Addresses to functions

    > Addresses of actual arguments in the calling function are copied intoformal arguments of the called function.

    > Changes made in the formal arguments reflects on the actualarguments.

    >Following program illustrates this fact:

  • 8/3/2019 P10_PointersInC

    31/41

    2.31

    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

  • 8/3/2019 P10_PointersInC

    32/41

    2.32

    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;

    }

  • 8/3/2019 P10_PointersInC

    33/41

    2.33

    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 inthe variables,would make change effective even in main()

  • 8/3/2019 P10_PointersInC

    34/41

    2.34

    Functions returning pointers

    > Function can even return a pointer,like it return int,float,a double oranother data type.

    > To make a function return a pointer,it has to be explicitly mentionedin the calling function as well as in the function definition.

  • 8/3/2019 P10_PointersInC

    35/41

    2.35

    Functions returning pointers

    /*Example*/

    #include

    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);

    }

  • 8/3/2019 P10_PointersInC

    36/41

    2.36

    Typecasting

    > To convert one type of variable to other type.

    > General form:(type) expression

    > Operation tellc to compute the value of the expression, and thenconvert it to specific type.

    > This is useful when you work with integers and floating pointnumbers.

  • 8/3/2019 P10_PointersInC

    37/41

    2.37

    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 willcompute the correct ratio */

    ratio =((float) won) / ((float) lost);

    It is also used to convert pointers of one type to other.

  • 8/3/2019 P10_PointersInC

    38/41

    2.38

    Roadmap

    > Summary

  • 8/3/2019 P10_PointersInC

    39/41

    2.39

    Pointers

    A pointerholds theaddress of anobject

    Use them to access and update variables: *ip = *ip + 1;

    Array variables behave like pointers to their firstelement

    int *ep = eightPrimes;

    Pointers can be treated like arrays: ep[7] = 23;

    But have different sizes: sizeof(eightPrimes) == 32)

    sizeof(ep) == 4)

    You may increment and decrement pointers: ep = ep+1;

    Declare a pointer to an unknown data type asvoid*

    void *vp = ep;

    But typecast it properly before using it! ((int*)vp)[6] = 29;

    int i = 10;

    int *ip = &i; /* assign address of i to ip */

  • 8/3/2019 P10_PointersInC

    40/41

    > I request Electronics and communication

    > ENGINEERING students to visit my blog for

    > more

    > abhishek1ek.blogspot.com> awhengineering.blogspot.com

    >

    2.40

  • 8/3/2019 P10_PointersInC

    41/41

    2.41