C Pointers and Arrays - PowerPoint PPT Presentation

1 / 40
About This Presentation
Title:

C Pointers and Arrays

Description:

Furthermore, old C style libraries are included by preceding the library name ... C style -- using references. void. SwapRef( int & A, int & B ) int Tmp = A; A = B; ... – PowerPoint PPT presentation

Number of Views:98
Avg rating:3.0/5.0
Slides: 41
Provided by: bill235
Category:

less

Transcript and Presenter's Notes

Title: C Pointers and Arrays


1
C Pointers and Arrays
  • CSCD 326

2
Variable Attributes
  • Attributes of a variable
  • Contents - the value stored in the memory
    location(s) used for the variable
  • Address - each byte of memory has a unique
    address which allows the CPU to access that
    memory location
  • Access to a named variables attributes
  • variable name - a reference to the value of the
    variable
  • e.g. x x 3
  • variable name - a reference to the address at
    which the variable is stored
  • e.g. x

3
Pointers and Indirect References
  • Pointers are variables used to store the address
    of another memory location
  • Pointers provide indirect access to a value
    stored in memory
  • Using the address stored in a pointer to access a
    value stored in that address is called
    dereferencing the pointer

Addresses
Contents
10A0
Pointer
2000
5
2000
4
C Pointer syntax
  • Declaration of a pointer object (variable)
  • int Ptr
  • this declares an object or variable called Ptr
    which can contain the address of an integer
    object
  • Pointer Assignment
  • int X 5
  • int Y 7
  • Ptr Y //Y is the address of Y

Name
Contents
Ptr
1008
7
X
5
Ptr
Y
Y
7
5
Dereferencing Operator
  • Allows access to the value of the data whose
    address is contained in a pointer for use in an
    expression or assignment
  • Ptr evaluates to 7
  • Ptr 15 -- assigns value 15 to the integer
    whose address is contained in Ptr
  • is the opposite of so (X) is the same as
    X

Name
Contents
Ptr
1008
15
X
5
Ptr
Y
Y
15
6
Pointer Example
  • include ltiostream.hgt
  • include ltstdlib.hgt
  • void
  • main()
  • int ptr, i 15
  • // assignment of addresses to a pointer variable
  • ptr NULL
  • ptr (int )0xfffe
  • ptr i
  • cout ltlt "address of i " ltlt ptr ltlt "\n"
  • cout ltlt "contents of i " ltlt ptr ltlt "\n"

7
Pointer Example Output
  • address of i 0x0012FF78
  • contents of i 15
  • Press any key to continue

8
Pointer expressions
  • include ltstdlib.hgt
  • include ltiostream.hgt
  • void
  • main()
  • int i 3, j 5, k
  • int p i, q j, r
  • (r k) p q
  • cout ltlt "r " ltlt r
  • Output
  • r 15

9
Pointer expressions memory
3
i
5
j
k
i
p
j
q
r
10
Arrays and Pointers
  • int SmallArray 1,3,5,7,9
  • int Iptr
  • Iptr SmallArray

Address
Name
1000
1
SmallArray
1004
3
5
1008
1000
7
100C
9
1010
1000
1014
Iptr
11
Array address calculations
Address
Name
1000
1
SmallArray
1004
3
5
1008
1000
7
100C
9
1010
1000
1014
Iptr
  • To determine the address of SmallArrayI
  • compiler calculates - SmallArray (I 4)
  • or 1000 (I 4)

12
Pointer Arithmetic
  • Pointer arithmetic can be used in the same way as
    array notation to access array members
  • Recall from previous example
  • Iptr SmallArray
  • the members of SmallArray can now be accessed as
  • (Iptr 1) (Iptr 2) etc.
  • or as (SmallArray 1) (SmallArray 2)
  • Since both Iptr and SmallArray are pointers,
    these expressions are pointer arithmetic
  • (Iptr I) is evaluated as
  • Iptr (I sizeof(Iptr)) or Iptr (I 4) in
    this case
  • So - (SmallArray I) is the same as
    SmallArrayI

13
Pointer Operators and precedence
  • Shown below is the top of the C precedence
    chart
  • consider the following expressions
  • int X5, Ptr X
  • Ptr Ptr X0 Ptr0
  • X2

14
Strings
  • C has its own string type and can be accessed
    via the standard template library (STL).
  • More specifically, you include ltstringgt and
    follow it with the statement using namespace
    std.
  • The using namespace std further requires that
    all other C header files are included without a
    .h.
  • Furthermore, old C style libraries are included
    by preceding the library name with a c (once
    again the .h is left off)
  • C type strings are still supported and we will
    use them- you may use your own user-defined
    string classes in programs

15
C type Strings
  • C strings are arrays of characters in which the
    end of the string is indicated by a char
    containing 0 (character constant \0)
  • the string array must be large enough to
    accommodate the extra terminal character
  • C strings are of type char or const char
  • char astr7
  • int i
  • OR
  • astr0 s (astr) s
  • astr1 t (astr 1) t
  • astr2 r (astr 2) r
  • astr3 i (astr 3) i
  • astr4 n (astr 4) n
  • astr5 g (astr 5) g
  • astr6 \0 (astr 6) \0

16
C String Functions
  • include ltstring.hgt
  • char strcpy(char , const char )
  • char strcat(char , const char )
  • int strcmp(const char , const char )
  • size_t strlen(const char )
  • strcpy- copies characters from its second
    parameter to its first - returns the address of
    the string copied to
  • strcat - adds characters in second parameter to
    the end of the first

17
C String Functions (cont)
  • strcmp- compares characters from second argument
    to those from first - return value indicates
    either equality or which string is larger
  • return value
  • lt0 - string1(first arg) less than string2
  • 0 - the strings are identical
  • gt 0 - string1 is greater than string2
  • strlen - counts characters in its argument - up
    to but NOT including the terminal 0 and returns
    this count

18
String Constants
  • Specified with quotes -- string
  • Placed into memory allocated by the compiler with
    the nul terminator added
  • thus string occupies 7 bytes of memory
  • Uses of string constants
  • can be used anywhere both a string and a constant
    can - e.g. as the second (but not first)
    parameter to strcpy
  • as array initializers char str10 string
    here characters are copied from the constant to
    the array
  • assignment to pointers char mystr string
    here the address of the memory location of the
    constant is assigned to mystr

19
Pointer Hopping
  • include ltstdio.hgt
  • void strcpy1(char s,char t)
  • void strcpy2(char s,char t)
  • void strcpy3(char s,char t)
  • void strcpy4(char s,char t)
  • void main(void)
  • char s150, s2
  • s2 "this is a literal string"
  • printf("s1 s\ns2 s\n",s1,s2)
  • //cout ltlt s1 ltlt s1 ltlt \ns2 ltlt s2 ltlt
    \n
  • strcpy1(s1,s2)
  • printf("s1 s\ns2 s\n",s1,s2)

20
Pointer Hopping (2)
  • void
  • strcpy1(char s,char t)
  • int i
  • i 0
  • while((si ti) ! '\0')
  • s
  • t
  • void
  • strcpy2(char s, char t)
  • while((s t) ! '\0')
  • s
  • t

21
Pointer Hopping (3)
  • void
  • strcpy3(char s, char t)
  • while((s t) ! '\0')
  • void
  • strcpy4(char s, char t)
  • while(s t)

22
Dynamic Memory Allocation
  • The new and delete operators can be used to
    allocate variable sized blocks of memory for
    classes, structures and arrays while a program is
    running
  • static allocation (at the start of a program or
    function) often requires too much memory to be
    allocated and wasted
  • example of dynamic array allocation
  • char str
  • str new char5 // allocates 5 bytes
  • Assert(str)
  • strcpy(str, test)
  • delete str
  • str NULL

23
Memory Leaks
  • Happen any time memory allocated with new is not
    returned with delete
  • Scope related example
  • void
  • F( int i )
  • int A110
  • int A2 new int 10
  • G(A1)
  • G(A2)
  • When scope is exited memory from automatic array
    A1 is freed but not memory pointed by A2 - 10
    ints leak - delete A2 would fix

24
Extending Arrays
  • The new and delete operators can be used to
    reallocate arrays during program execution to
    make them larger
  • the following program reads an infinite number of
    integers - until 0 is read - and stores them in
    an extensible array

25
  • include ltiostreamgt
  • include ltcstdlibgt
  • using namespace std
  • // Read an unlimited number of ints.
  • // Return a pointer to the data, and set
    ItemsRead.
  • int
  • GetInts( int ItemsRead )
  • int ArraySize 0
  • int InputVal
  • int Array 0 // Initialize to NULL
    pointer
  • ItemsRead 0
  • cout ltlt "Enter any number of integers "
  • while( cin gtgt InputVal )
  • if( ItemsRead ArraySize )

26
include ltnewgt //allows us to handle memory
exceptions using namespace std main( ) int
Array int NumItems // The actual
code try Array GetInts( NumItems )
for( int i 0 i lt NumItems i )
cout ltlt Array i ltlt '\n' catch(
bad_alloc exception ) cerr ltlt "Out of
memory!" ltlt endl exit( 1 ) return
0
27
Memory Exhaustion
  • A mechanism is needed to report when dynamically
    allocated memory (heap) is exhausted
  • C mechanism - new returns NULL pointer
  • C exception mechanism
  • VC 6.0 must include ltnewgt, which allows new
    to throw a C exception of type bad_alloc in the
    event of an allocation failure
  • in your code, you can use try/catch exception
    handling constructs to detect and handle
    bad_alloc exceptions

28
Reference Variables ( parameters)
  • A reference type is a pointer constant which is
    always dereferenced implicitly
  • example
  • int LongVariableName 0
  • int Cnt LongVariableName
  • Cnt 3
  • reference variables must be initialized - they
    are constants
  • reference variable names are implicitly
    dereferenced unlike all other pointer types
  • example of reference types as parameters

29
Swap Functions
  • include ltiostream.hgt
  • void SwapWrong( int A, int B )
  • void SwapPtr( int A, int B )
  • void SwapRef( int A, int B )
  • // Simple program to test various Swap routines
  • main( )
  • int X 5
  • int Y 7
  • SwapWrong( X, Y )
  • cout ltlt "X" ltlt X ltlt " Y" ltlt Y ltlt '\n'
  • SwapPtr( X, Y )
  • cout ltlt "X" ltlt X ltlt " Y" ltlt Y ltlt '\n'
  • SwapRef( X, Y )
  • cout ltlt "X" ltlt X ltlt " Y" ltlt Y ltlt '\n'

30
  • // Does not work
  • void
  • SwapWrong( int A, int B )
  • int Tmp A
  • A B
  • B Tmp
  • // C Style -- using pointers
  • void
  • SwapPtr( int A, int B )
  • int Tmp A
  • A B
  • B Tmp
  • // C style -- using references

31
2D Arrays and Pointers (1)
  • include ltstdio.hgt
  • void main(void)
  • int array34,i,j,val0
  • for(i0i lt 3 i)
  • for(j0 j lt 4 j)
  • arrayij val
  • printf("arraydd
    d\n",i,j,arrayij)
  • printf("array x\n",array)
  • printf("array0 x\n",array0)
  • printf("array1 x\n",array1)
  • printf("array1 d\n",array1)
  • printf("array1 x\n",array1)
  • printf("array2 d\n",array2)
  • printf("array2 x\n",array2)
  • printf("array2 d\n",array2)
  • printf("((array1)2) d\n",((array1)2))

32
2D Arrays and Pointers (2)
  • array00 0
  • array01 1
  • array02 2
  • array03 3
  • array10 4
  • array11 5
  • array12 6
  • array13 7
  • array20 8
  • array21 9
  • array22 10
  • array23 11
  • array effff804
  • array0 effff804
  • array1 effff814
  • array1 4
  • array1 effff808
  • array2 8
  • array2 effff80c
  • array2 2
  • ((array1)2) 6
  • (array1)2 effff81c
  • array3 0

33
2D Arrays and Pointers (3)
  • array effff804
  • array0 effff804
  • array1 effff814
  • array1 4
  • array1 effff808
  • array2 8
  • array2 effff80c
  • array2 2
  • ((array1)2) 6
  • (array1)2 effff81c
  • array3 0

array -- effff804 (804) each row contains 16 bytes
array0
array1
array2
34
Pointers and Structures
  • Structures are an aggregate data type of
    different types
  • struct Student
  • char FirstName40
  • char LastName40
  • int StudentNum
  • double GradePointAvg
  • Student S
  • declares and allocates an entire structure named
    S
  • Student Sptr S
  • declares, allocates and initializes a pointer
    Sptr which points at S

35
Struct member access through pointers
  • One way to access the members of S through Sptr
    is
  • (Sptr).GradePointAvg
  • since this is awkward at best, an operator has
    been provided which both dereferences and
    provides member selection
  • Sptr-gtGradePointAvg
  • this has exactly the same meaning as the previous
    expression

36
Structs as parameters
  • Call by value prototype
  • void PrintInfo( Student ThisStudent)
  • results in a copy being made of the entire actual
    parameter
  • Call by reference prototype
  • void PrintInfo( Student ThisStudent )
  • since only the address of the actual parameter is
    passed no copy is made
  • Call by constant reference parameter
  • void PrintInfo( const Student ThisStudent)
  • here no copy is made and no changes can be made
    to the actual parameter

37
Exogenous vs. Indigenous Data
  • The student struct as illustrated before contains
    all indigenous data - All data is contained
    inside the stuct
  • Exogenous data - data allocated outside the
    struct but pointed to by an internal pointer
  • Example
  • struct Student
  • char FirstName
  • char LastName
  • int StudentNum
  • double GradePointAvg
  • Student S
  • S.FirstName new char 40
  • S.LastName new char 40

38
Problems with Exogenous Data
  • In the previous example suppose we have
  • Student S, T
  • if T has been initialized and had space allocated
    for its strings then
  • S T
  • does a member by member copy of T into S which
    means they have pointers to the same FirstName
    and LastName strings - thus
  • delete T.FirstName erases the string
    pointed to by S.FirstName
  • overriding the operator and copying only
    pointers is a shallow copy
  • overriding the operator and copying the memory
    holding characters is a deep copy

39
Linked List Basics
  • Arrays can be thought of as lists of objects
    which occupy contiguous memory
  • Using structures and pointers a list of objects
    which are located in non-contiguous memory can be
    built
  • the basic structure for such a list is shown
    below
  • struct Node Diagram
  • char Element
  • Node next

Element
Next
40
Linked List Building
  • void main()
  • Node head NULL, cur
  • char c
  • for(c a c lt z c)
  • if(!head)
  • head cur new Node
  • head-gtElement c
  • else
  • cur-gtNext new Node
  • cur cur-gtNext
  • cur-gtElement c
Write a Comment
User Comments (0)
About PowerShow.com