11267 Pointers

download 11267 Pointers

of 49

Transcript of 11267 Pointers

  • 8/3/2019 11267 Pointers

    1/49

    PointersPointers

  • 8/3/2019 11267 Pointers

    2/49

    VariableVariable

    y A variable is a named memory location.

    y Variables provide direct access to its memory

    location.y A variable has a name, an address, a type,and a

    value:

    y

    "the name identifies the variable to theprogrammer

    y "the address specifies where in main memorythe variable is located

  • 8/3/2019 11267 Pointers

    3/49

    What is a variable?What is a variable?

    y "the type specifies how to interpret the

    data stored in main memory and howlong the variable is

    y "the value is the actual data stored in the

    variable after if has been interpreted

    according to a given type

  • 8/3/2019 11267 Pointers

    4/49

    Pointer variablePointer variabley A pointer is a variable that contains the memory

    location ofanother variable.

    y Syntax:-

    y type * variable namey You start by specifying the type of data stored in the

    location identified by the pointer.

    y The asterisk tells the compiler that youare creating a

    pointer variable.

    y Finally you give the name of the variable.

  • 8/3/2019 11267 Pointers

    5/49

    Declaring a Pointer VariableDeclaring a Pointer Variable

    To declare ptr as an integer pointer:

    int *ptr;

    To declare ptr as a character pointer:

    char *ptr;

  • 8/3/2019 11267 Pointers

    6/49

    Address operator:Address operator:

    y Once we declare a pointer variable we mustpoint it to something we can do this byassigning to the pointer the address of the

    variable you want to point as in the following

    example:

    ptr=#

    y This places the address where num is stores

    into the variable ptr. If num is stored inmemory 21260 address then the variable ptrhas the value 21260.

  • 8/3/2019 11267 Pointers

    7/49

    Address and PointersAddress and Pointers

    y Memory can beconceptualized as alinear set of datalocations.

    y Variables reference thecontents ofalocations

    y Pointers have a valueof the address ofagiven location

    Lect 14 P. 7

    Contents1

    Contents11

    Contents16

    ADDR1ADDR2ADDR3ADDR4

    ADDR5ADDR6***

    ADDR11

    **

    ADDR16

  • 8/3/2019 11267 Pointers

    8/49

    Pointer VariablePointer VariableAssume ptr is a pointer variable and x is an integer variable

    x

    ptr

    x = 10

    10

    ptr = &x

    &x

    Now ptrcanaccessthe value ofx.

    HOW!!!!

    Write: *variable . Forexample:

    printf(%d\n, *ptr);

    Can youtellme why weput%d????

  • 8/3/2019 11267 Pointers

    9/49

    Variables, Addresses and PointersVariables, Addresses and Pointers

    y main()

    {

    int a = 5;

    int b = 6;

    int* c;

    // c points to a

    c = &a;}

    y MemoryValue

    y a (1001) 5

    y b (1003) 6

    y c (1005) 1001

  • 8/3/2019 11267 Pointers

    10/49

    include< stdio.h >

    {int num, *intptr;

    float x, *floptr;char ch, *cptr;num=123;

    x=12.34;

    ch=a;intptr=&num;cptr=&ch;floptr=&x;

    printf(Num %d stored at address %u\n,*intptr,intptr);

    printf(Value %f stored at address %u\n,*floptr,floptr);printf(Character %c stored at address %u\n,*cptr,cptr);}

  • 8/3/2019 11267 Pointers

    11/49

    Run this codeRun this code

    int main()

    {

    int x;

    int *ptr;

    x = 10;

    ptr = &x;

    *ptr = *ptr + 1;

    printf(x = %d\n, x);

    }

  • 8/3/2019 11267 Pointers

    12/49

    Manipulating Pointer VariableManipulating Pointer Variable

    y Once a variable is declared, we can get its address bypreceding its name with the unary & operator, asin &k.

    y We can "dereference" a pointer, i.e. refer to the value

    of that which it points to, by using the unary '*'operator as in *ptr

  • 8/3/2019 11267 Pointers

    13/49

    ReferenceReference

    y Reference &

    y Retrieve the memory address of a variable

    y int a = 6;

    y int* c = &a; // &a is the memory location of variable a

  • 8/3/2019 11267 Pointers

    14/49

    DereferenceDereference

    y Dereference * Accessing the variable (content)the pointer points to

    y (Indirection)

    y int a = 6;

    y int* c = &a;

    y *c = 7; /* Changes content of variable a by

    using its address stored in pointer c */y equivalent to

    y a = 7;

  • 8/3/2019 11267 Pointers

    15/49

    Constant PointersConstant Pointers

    y A constant pointer,ptr, is a pointer that

    is initialized with an address, and cannotpoint to anything else.

    yWe can useptr to change the contentsof value

    y Example

    int value = 22;int * constptr = &value;

    CIS 15 Pointer Arithmetic 15

  • 8/3/2019 11267 Pointers

    16/49

    Constant PointerConstant Pointer Constant pointer means the pointer is constant.Constant pointer is NOT pointer to constant. For eg:

    int * const ptr2 indicates that ptr2 is a pointerwhich is constant. This means that ptr2 cannot bemade to point to another integer.

    However the integer pointed by ptr2 can bechanged.

  • 8/3/2019 11267 Pointers

    17/49

    //const pointer void

    main()

    {

    int i = 100,k;

    int* const pi =&i;

    *pi = 200;

    pi=&k; //won't compile

    }

  • 8/3/2019 11267 Pointers

    18/49

    Constant Pointers to ConstantsConstant Pointers to Constants

    A constant pointer to a constant is:y a pointer that points to a constant

    y a pointer that cannot point to anything

    except what it is pointing to

    Example:int value = 22;

    const int * const ptr =&value;

    CIS 15 Pointer Arithmetic 18

  • 8/3/2019 11267 Pointers

    19/49

    y //const pointer to a const void

    y f3()

    y {

    y int i = 100;

    y const int* const pi =&i;

    y //*pi = 200;

  • 8/3/2019 11267 Pointers

    20/49

    Pointer to constantPointer to constant

    Pointer to constant is

    const int * ptr1 indicates that ptr1 is a

    pointer that points to a constant integer.The integer is constant and cannot be

    changed.However, the pointer ptr1 can

    be made to point to some other integer.

  • 8/3/2019 11267 Pointers

    21/49

    y //pointer to a const

    void f1()

    {

    int i = 100;

    const int* pi =&i;

    //*pi = 200;

  • 8/3/2019 11267 Pointers

    22/49

    Pointer arithmeticPointer arithmetic

    Valid operations on pointers include:

    - the sum of a pointer and an integer

    - the difference of a pointer and an integer

    - pointer comparison

    -the difference of two pointers.

    -Increment/decrement in pointers

    -assignment operator used in pointers

  • 8/3/2019 11267 Pointers

    23/49

    ExampleExample

    void main(){

    int a=25,b=78,sum;

    int *x,*y;x=&a;

    y=&b;

    sum= *x + *y;

    printf(Sum is : %d,sum);

    }

  • 8/3/2019 11267 Pointers

    24/49

    Assignment in pointersAssignment in pointers

    y Pointer variables can be "assigned":int *p1, *p2;p2 = p1;

    Assigns one pointer to another "Make p2 point to where p1 points"

    y Do not confuse with:*p1 = *p2;

    Assigns "value pointed to" by p1, to "valuepointed to" by p2

  • 8/3/2019 11267 Pointers

    25/49

    Diagrammatic representationDiagrammatic representation

  • 8/3/2019 11267 Pointers

    26/49

    Comparison in pointersComparison in pointers

    y Two pointers of the same type, p and q, may becompared as long

    y as both of them point to objects within a single memory

    blocky Pointers may be compared using the , =,

    == , !=

    y When youare comparing two pointers, youare

    comparing the

    y values of those pointers rather than the contents ofmemorylocations pointed to by these pointers

  • 8/3/2019 11267 Pointers

    27/49

    Increment and decrementIncrement and decrement

    Data Type Initialaddress

    Operation Addressafter

    operation s

    Requiredbytes

    Int i=2 4046 ++ -- 4048 4044 2bytes

    Char c=x 4053 ++ -- 4054 4042 1bytes

    Float f=2.2 4050 ++ -- 4054 4046 4bytes

    Long l=2 4060 ++ -- 4064 4056 4bytes

  • 8/3/2019 11267 Pointers

    28/49

  • 8/3/2019 11267 Pointers

    29/49

    y You can add an integer to a pointer but you cannot add a pointer to apointer.

    y

    If the pointer p points to the first element in an array, the followingexpression causes the pointer to point to the third element in the samearray:

    y p = p + 2; If you have two pointers that point to the same array, you cansubtract one pointer from the other. This operation yields the number ofelements in the array that separate the two addresses that the pointers

    refer to.y You can compare two pointers with the following

    operators: ==, !=,< ,>,=.

    y Pointer comparisons are defined only when the pointers point toelements of the same array. Pointer comparisons usingthe == and != operators can be performed even when the pointers point

    to elements of different arrays.y You can assign to a pointer the address ofa data object, the value of

    another compatible pointer or the NULL pointer.

  • 8/3/2019 11267 Pointers

    30/49

    Pointer ArithmeticPointer Arithmetic

    y Operations on pointer variables:

    CIS 15 Pointer Arithmetic 30

    Operation Exampleint vals[]={4,7,11};

    int *valptr = vals;++, -- valptr++; // points at 7

    valptr--; // now points at 4

    +, - (pointerand int) cout

  • 8/3/2019 11267 Pointers

    31/49

    Generic pointersGeneric pointers

    yWhen a variable is declared as being a pointerto type void it is known as a generic pointer.

    y Since you cannot have a variable of type void,

    the pointer will not point to any dataandtherefore cannot be dereferenced.

    y It is stilla pointer though, to use it youjust

    have to typecast it to another kind of pointerfirst.Hence the termGeneric pointer.

  • 8/3/2019 11267 Pointers

    32/49

    y This is very useful when you want a pointer to

    point to data of different types at differenttimes.

    y Syntax:

    void * variable name;

    Print value stored in variable

    *(data_type*)name of variable;

  • 8/3/2019 11267 Pointers

    33/49

    void main()

    { int i;

    char c;

    void *data;

    i = 6;

    c = 'a';

    data=&i;

    printf("the_data points to the integer value %d\n", *(int*)data);

    data=&c;

    printf("the_data now points to the character %c\n", *(char*)

    data);

    }

  • 8/3/2019 11267 Pointers

    34/49

    Null PointerNull Pointer

    y NULL value can be assigned to any pointer, nomatter what its type.

    y

    void *p = NULL;y int i = 2;

    y int *ip =&i;

    y

    p = ip;y printf("%d", *p);

    y printf("%d", *((int*)p ) );

  • 8/3/2019 11267 Pointers

    35/49

    Pointers and ArraysPointers and Arrays

    The concept ofarray is very much bound to

    the one of pointer. In fact, the identifier of

    an array is equivalent to the address of its

    first element, as a pointer is equivalent to

    the address of the first element that it

    points to, so in fact they are the same

    concept.

  • 8/3/2019 11267 Pointers

    36/49

    Pointers and ArraysPointers and Arrays

    y Pointers have close relationship with array

    .

    y An array name by itself is an address or

    pointer.

    y Pointers are linked with both types of

    array

    A)one dimensionalarray pointer B)two dimensionalarray pointer

  • 8/3/2019 11267 Pointers

    37/49

    For example,

    int numbers [20]; int * p;

    The following assignment operationwould be valid:

    p = numbers;

  • 8/3/2019 11267 Pointers

    38/49

  • 8/3/2019 11267 Pointers

    39/49

  • 8/3/2019 11267 Pointers

    40/49

    *p = 30;p = numbers + 3;

    *p = 40; p = numbers;

    *(p+4) = 50;for(int n=0; n

  • 8/3/2019 11267 Pointers

    41/49

    In arrays we used brackets ([]) several times

    in order to specify the index ofan element

    of the array to which we wanted to refer.

    Well, these bracket sign operators [] are

    also adereference operator known as

    offset operator. They dereference the variable

    they follow just as * does, but they also add

    the number between brackets to the

    address being dereferenced

  • 8/3/2019 11267 Pointers

    42/49

    For example:

    a[5] = 0; // a [offset of 5] = 0

    *(a+5) = 0; // pointedby (a+5) = 0

    These two expressions are equivalent andvalid both ifa is a pointer or ifa is an

    array.

  • 8/3/2019 11267 Pointers

    43/49

    Example ofExample of1D array1D arrayV

    oid main(){

    int a[5]={1,2,3,4,5};

    int *p,i;

    p=&a;

    printf(displaying data using pointer );for(i=0;i

  • 8/3/2019 11267 Pointers

    44/49

    Example ofExample of2D array2D array

    Void main()

    {

    int a[5][2]={ {1,2},{3,4},{5,6},{7,8},{9,10} };

    int *p,j,i;

    p=&a;

    printf(displaying data using pointer );

    for(i=0;i

  • 8/3/2019 11267 Pointers

    45/49

    Pointers and Character StringPointers and Character String

    void main(){

    char name[] = sanjima;

    char *ptr;

    int i=0;count=0;ptr=&name;

    while(*(ptr+i)!=\0)

    {

    count++;i++;

    }

    printf(length of string is %d ,count);

    getch();

  • 8/3/2019 11267 Pointers

    46/49

    ExampleExample

    void main(){

    char str1[]=hello;char str2[10];

    char *s= Good Morning;char *q;

    str2=str1; /error/

    q= s; /works/return;}

  • 8/3/2019 11267 Pointers

    47/49

    Array of pointersArray of pointers

    y It is nothing but a collection of address.

    Void main()

    {

    int a[5]={1,2,3,4,5},i;

    int *p[5];

    for(i=0;i

  • 8/3/2019 11267 Pointers

    48/49

    Pointers to pointersPointers to pointersy

    A pointer variable containing address ofanother pointer variable is called pointer

    to pointer

    void main()

    {

    int a=2, *p, **q;

    p=&a;

    q=&p;

    printf(%d value is stored at %uand pointer

    is stored at %u,a,p,q);}

  • 8/3/2019 11267 Pointers

    49/49