Section 7 Pointers and Arrays - PowerPoint PPT Presentation

1 / 7
About This Presentation
Title:

Section 7 Pointers and Arrays

Description:

X. Liu 2004. Section 7 Pointers and Arrays. Pointer is one of the most important features of C ... X. Liu 2004. Pointer Basics. To assign a variable's ... – PowerPoint PPT presentation

Number of Views:66
Avg rating:3.0/5.0
Slides: 8
Provided by: ceb245elec
Category:

less

Transcript and Presenter's Notes

Title: Section 7 Pointers and Arrays


1
  • Section 7 Pointers and Arrays
  • Pointer is one of the most important features of
    C
  • 7-1 Pointers and Addresses
  • (with more than 10 examples)
  • A typical computer has an array of consecutively
    numbered hardware cells
  • This array is called the memory, and the number
    of a cell is called the address
  • Just like a set of rooms, each having a
    room-number, and somebody inside it
  • A simplified picture of memory

2
00100000 00100001 00100010 00100011 00100100
00100101 00100110 00100111 00101000 00101001
00101010 00101011
10110111
00100010
3
  • A pointer is a C variable used to hold the
    MEMORY ADDRESS
  • of another item
  • Example 1
  • x10110111 px00100010
  • then px is a pointer that points to x
  • An item can be
  • A basic variable whose type is int, float,
    double, char.
  • An array element
  • Another pointer
  • A structure (user defined data type)
  • A function

4
  • Pointer Declaration
  • To declare a pointer variable, put a in front
    of the name of the variable
  • Example 2
  • char x, px
  • float y, py
  • int i, pi
  • px is a pointer that holds the memory address of
    a char variable
  • py is a pointer that holds the memory address of
    a float variable
  • pi is a pointer that holds the memory address of
    an int variable

5
  • Pointer Basics
  • To assign a variables MEMORY ADDRESS to a
    pointer, use operator
  • x means address of x
  • Example 3
  • char x,px
  • short i,pi
  • px x
  • pi i
  • px now holds the MEMORY ADDRESS of x (x is
    pointed to by px)
  • pi now holds the MEMORY ADDRESS of i(i is
    pointed to by pi)

6
  • To store/retrieve a value in/from a variable
    pointed to by a pointer, use the Indirection
    operator
  • z means the content of the cell whose address
    is z
  • Example 4
  • double x,y,px
  • pxx (x is pointed to by px)
  • px3.0 (a value of 3.0 is now stored in x)
  • ypx (this is equivalent to yx)

7
  • Example 5 (pointer pitfall)
  • Dont put a value into a location with the
    unknown memory address
  • int q, p
  • (At this moment, p itself has not been
    initialized yet!)
  • (You should not put anybody into a room with an
    unknown room-number)
  • p5
  • No compiler error or run-time error
  • Value 5 is stored in an unknown memory location
    (Your program may crash!)
Write a Comment
User Comments (0)
About PowerShow.com