pointer variables

Download Pointer Variables

Post on 30-Dec-2015

20 views

Category:

Documents

2 download

Embed Size (px)

DESCRIPTION

Pointer Variables. A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer “points” to the other variable in memory A pointer is declared using the general statement: type *name;e.g.int *i1;. - PowerPoint PPT Presentation

TRANSCRIPT

  • Pointer VariablesA pointer is a variable that contains a memory address

    The address is commonly the location of another variable in memory

    This pointer points to the other variable in memory

    A pointer is declared using the general statement:

    type *name;e.g.int *i1;

  • Important Uses of PointersAllows functions to modify their arguments

    Supports dynamic memory allocation functions

    Improves the efficiency of certain routines

    Allows communication to other functions, programs, and hardware using shared memory and memory transfers

    Pointers are one of the most powerful features of C/C++ but are also the most dangerous

  • Pointer Operators&breturn the memory address of variable b*preturn the value of the variable at address p* is the complement of & so that *(&b)=b

    These operators have a higher precedence than other arithmetic operators except urinary minus which is equalint b = 7777, *p;p = &b;cout

  • A Variable Pointing to Another Variablepi1*p

    Memory addressVariable in memory1000100310011002100377771004

  • Pointer Expressionsp = qpointer assignmentp++, p--increment and decrementp = p + iaddition of an integer ip = p - isubtraction of an integer ip == qtest for equalityp < q , p > qpointer comparison

  • char *ch = 3000;int *i = 3000;

    expressionMemory (bytes)expressionch3000ich + 13001ch + 23002ch + 33003ch + 43004i + 1ch + 53005

  • Pointers and ArraysA 1D array is equivalent to a pointer to the first element

    There are two ways of accessing arrays: pointer arithmetic and array indexing, s1[i]=*(s1+i)

    Indexing can also be used on pointer variables

    char s1[6] = peach, *p1; p1 = s1; cout

  • Passing Pointers and Arrays to Functions1D arrays and pointers are interchangeable when passing arguments to functions

    Since the memory location is passed to the function it will modify the contents of the array: call by reference

    No copies of the array are made when passed to the function

    Be sure to know the boundaries of the array to avoid invalid memory access

  • Modifying Function ArgumentsPointers allow C functions to modify their arguments

    call by valueint i = 0; fun1(i); cout

  • Array Swappingint ar[2]={1,2}, br[2]={3,4};int *a=ar,*b=br,*c;c = a;a = b; b = c;cout
  • Initializing PointersAlways initialize your pointers to valid memory locations

    A pointer initialized incorrectly is called a wild pointer

    Reading data from a wild pointer will return garbage

    Writing data to a wild pointer could overwrite program, data or operating system memory, e.g.int x, *p;x = 10; *p = x;

  • Common Problems With Pointersint x, *p;x = 10; p = x;cout
  • Dynamic Memory Allocationstatic arrays allocate memory at the beginning of program executionchar s1[10], *p1;p1 = s1;dynamic memory is allocated during program execution#include #include char *p1;p1 = (char *)malloc(10*sizeof(char));

  • Dynamic ArraysDynamic arrays are useful because the size of the array can be determined at run-time

    The size of the array can be made just small enough for the application

    The memory allocated can also be freed for other functions to use when it is no longer needed

    It must be freed before the program is finished using the functionfree(p1)

  • New and Delete OperatorsC++ provides operators for dynamic memory allocationp = new type [size];// new operator for allocationdelete p; // delete operator for freeing memoryint *p1; char *p2;p1 = new int;p2 = new char [5];*p1 = 8;strcpy(p2,ball);cout
  • Comparison with C Allocation RoutinesNew and delete have the following advantages over malloc and free:

    Automatically computes the size needed in bytes

    Automatically returns a pointer of a specified type

    Provides support for C++ features related to operator overloading, initialization, constructors, and destructors

    Note that both malloc and new can take longer to run than static memory allocation for large blocks of memory

  • Arrays of PointersArrays of pointers can be declared like any other type

    char *pa[2];char p1[]="hello", p2[]="goodbye";pa[0] = p1;pa[1] = p2;cout

  • papa[0]pa[1]

    memory addressvariable9001000100010081004100E1008h1009e100Al100Bl100Co100D\0100Eg100Fo

  • Pointers to PointersSince pointers are stored in memory we can declare pointers to them as wellchar **pp;char *p, s[]="MJ";p = s; // point to the string pp = &p; // get the pointer to pcout
  • ppp , s**pp*pp

    memory addressvariable10001004100110021003100410081005100610071008M1009J

  • papa[0]pa[1]pppp[0]pp[1]

    memory addressvariable9001000100010081004100E1008h1009e100Al100Bl100Co100D\0100Eg100Fo

  • Why Pointers ?Allows functions to modify their arguments

    Supports dynamic memory allocation functions

    Improves the efficiency of certain routines (swapping, )

    Allows communication to other functions, programs, and hardware using shared memory and memory transfers

    Useful for passing functions to other functions

    Important for developing multidimensional dynamic arrays

  • Key Things to RememberA 1D array is the same as a pointer to the first elementdouble s[2] = { 1.0, 2.0 }, *p; p = s;p[1] == s[1] == *(p+1) == *(s+1) == 2We can dynamically allocate a 1D array using newdouble *p;int n = 10;p = new double [n]; p[1] = 1.0; delete p;We can also have a 1D array of pointers which is the same as a pointer to a pointerdouble *pa[10], **pp;pp = pa;

  • More on Static Multidimensional Arrays2D static arrays are stored in a row by row formatint a[2][3] = {1,2,3,4,5,6}; a =int *r0, *r1, i;r0 = a[0]; r1 = a[1];for(i=0;i
  • Limitations of Static Multidimensional ArraysThey cannot be passed to general functions since arrays of different sizes cannot be used interchangeably

    int a[4][4]; a[0][0] = 1;f1(a); cant convert int[4][4] to int[][3]int fun1(int a[3][3]) { return a[0][0]; }

    They also cannot be converted to a pointer to pointer

    Only use static multidimensional arrays for simple applications where the size is always fixed

  • Multidimensional Dynamic ArraysOne way to construct a 2D dynamic array:

    First allocate a 1D dynamic array of pointers

    This will have a pointer to pointer type

    Then initialize each array element to a 1D dynamic array that stores each rowdone !

    Dynamic arrays of any size can be passed to a function since they all have pointer to pointer type

  • Row SwappingRows of a dynamic array can be efficiently swapped by swapping the pointers to the rows

    int *pa[2], **m, r0[] = {1,2}, r1[] = {3,4}, *d;m = pa; m[0] = r0; m[1] = r1;cout

  • Pointers to Objectsclass string_class {public: char str[100]; void strcpy2(char *s);};void string_class::strcpy2(char *s) { strcpy(str,s); }string_class s1, *sp; s1.strcpy2(ya); sp = &s1;cout
  • Arrays of Objectsstring_class s1[3], *sp;s1[0].strcpy2(one); s1[1].strcpy2(two);s1[2].strcpy2(three); sp = s1;cout str
  • Dynamically Allocated Objectsstring_class *sp1,*sp2;sp1 = new string_class(apple); // initialize object to applesp2 = new string_class [3]; // cant initialize dynamic arrayssp2[0].strcpy2(peach);cout str

Recommended

View more >