Pointers and Arrays - PowerPoint PPT Presentation

1 / 17
About This Presentation
Title:

Pointers and Arrays

Description:

An array name can be thought of as a constant pointer. Pointers can be used to do operations involving arrays. ... [4] = {'Hearts', 'Diamonds', 'Clubs', 'Spades' ... – PowerPoint PPT presentation

Number of Views:25
Avg rating:3.0/5.0
Slides: 18
Provided by: ehyl
Category:

less

Transcript and Presenter's Notes

Title: Pointers and Arrays


1
Pointers and Arrays
  • Arrays and pointers are closely related in C
    and may be used almost interchangeably.
    An array name can be thought of as a
    constant pointer. Pointers can be used
    to do operations involving arrays. Assume that
    integer array b 5 and integer pointer variable
    bPtr have been declared. Because the array name b
    (without its subscript i.e 5) is a pointer to
    the first element of the array, we can set bPtr
    to the address of the first element in array b
    with the statement bPtrb
  • This is equivalent to taking the address of the
    first element of the array as follows bPtr
    b0

2
Pointers and Arrays
  • Array element b3 can alternatively be
    referenced with the pointer expression
    (bPtr3)
  • The 3 in the preceding expression is the offset
    to the pointer. When the pointer points
    to the beginning of an array, the offset
    indicates which element of the array should be
    referenced, and the offset value is identical to
    an array subscript i.e 3.
  • The preceding notation is referred to as
    pointer/offset notation. The parentheses are
    necessary, because the precedence of is higher
    than the precedence of .

3
Pointers and Arrays
  • Just as the array element can be referenced with
    a pointer expression, the address
    b3can be written with the pointer
    expression bPtr 3
  • The array name can be treated as a pointer and
    used in pointer arithmetic. For example, the
    expression (b3)also refers to the array element
    b3. In general, all subscripted array
    expressions can be written with a pointer and an
    offset. In this case, pointer/offset notation was
    used with the name of the array as a pointer.
    Note that this statement does not modify the
    array name in any way b still points to the
    first element in the array.

4
Pointers and Arrays
  • Pointers can be subscripted exactly as arrays
    can. For example, the expression
    bPtr1refers to the array element b 1
    this expression is referred to as
    pointer/subscript notation.
  • Remember that an array name is essentially a
    constant pointer it always points to the
    beginning of the array.
  • Thus, the expression b 3 is invalid, because
    it attempts to modify the value of the array name
    with pointer arithmetic.

5
Array Pointer Arithmetic
  • b5
  • index 0 1 2 3 4
  • bPtr b b0
  • bPtr 1
  • (bPtr 3) b3 4
  • b3 bPtr 3
  • (b 3) b3 4
  • bPtr1 b1 2

6
Pointers and Arrays
// Fig. 5.20 fig05_20.cpp // Using subscripting
and pointer notations with arrays include
ltiostreamgtusing stdcoutusing stdendl int
main() int b 10, 20, 30, 40 , i,
offset int bPtr b // set bPtr to point
to array b cout ltlt "Array b printed with\n"
ltlt "Array subscript notation\n" for ( i
0 i lt 4 i ) cout ltlt "b" ltlt i ltlt "
" ltlt b i ltlt '\n' cout ltlt "\nPointer/offset
notation where\n" ltlt "the pointer is the
array name\n" for ( offset 0 offset lt 4
offset ) cout ltlt "(b " ltlt offset ltlt ")
" ltlt ( b offset ) ltlt '\n'
cout ltlt "\nPointer subscript notation\n" for
( i 0 i lt 4 i ) cout ltlt "bPtr" ltlt i
ltlt " " ltlt bPtr i ltlt '\n' cout ltlt
"\nPointer/offset notation\n" for ( offset
0 offset lt 4 offset ) cout ltlt "(bPtr
" ltlt offset ltlt ") " ltlt ( bPtr offset ) ltlt
'\n' return 0
7
Pointers and Arrays

8
Pointers and Arrays
Pointer to a char
// Fig. 5.21 fig05_21.cpp Copying a string array
pointer notation include ltiostreamgtusing
stdcoutusing stdendl void copy1(char
,const char )void copy2(char ,const char
) int main() char string1 10 , string2
"Hello", string3 10 , string4 "Good
Bye" copy1( string1, string2 ) cout ltlt
"string1 " ltlt string1 ltlt endl copy2(
string3, string4 ) cout ltlt "string3 " ltlt
string3 ltlt endl return 0 // copy s2 to s1
using array notation void copy1( char s1, const
char s2 ) for ( int i 0 ( s1 i s2 i
) ! '\0' i ) // do nothing in
body // copy s2 to s1 using pointer
notation void copy2( char s1, const char s2 )
for ( ( s1 s2 ) ! '\0' s1, s2 )
// do nothing in body
10 element array on stack
Principle of least privilege is enforced here as
neither function requires the ability to modify
the second argument .so
neither is given it...
9
Pointers and Constants
  • When defining a pointer, the pointer itself, the
    value it points to or both can be made
    constant. The position of const in the
    definition determines which applies.int
    i,jconst intpi // p is a pointer to an int
    constant (p), p is not a constant.p5 is
    illegal (cannot change i using p), i5 ok as i
    not constant
  • int const pi // p is a pointer to a constant
    int (p), exactly the same as above
  • int const p i // p is a constant pointer to
    an int, i.e. p 5 ok, but p j is illegal
  • const int const p i // p is a constant
    pointer to an int constant, both p 5 and p j
    -gt illegal

10
Arrays of Pointers
  • Arrays may also contain pointers. i.e a string
    array in which each entry in the array is
    a string but in C a string is
    essentially a pointer to the first
    character.
  • const char suit4 Hearts, Diamonds,
    Clubs, Spades
  • Even though the suit array is fixed in size, it
    provides access to character strings of any
    length. This flexibility is one example of Cs
    powerful data structuring capabilities.

4 element array
Each element pointer to char
11
Function Pointers
  • A function name is the starting address in memory
    of the code that performs the functions
    task. i.e
  • The program that follows is a code snippet of a
    sorting algorithm. It consists of main, bubble,
    swap, ascending and descending functions.
  • The bubble function receives a pointer to a
    function (either the ascending or descending
    function) as an argument in addition to an
    integer array and the size of the array.
  • Function pointers also have use in menu driven
    applications.

12
Function Pointers
void bubble( int , const int, bool ()( int,
int ) ) bool ascending( int, int ) bool
descending( int, int ) int main() const int
arraySize 10 int order, counter, a
arraySize 2, 6, 4, 8, 10, 12, 89, 68, 45,
37 cout ltlt "Enter 1 to sort in ascending
order,\n" ltlt "Enter 2 to sort in descending
order " cin gtgt order cout ltlt "\nData
items in original order\n" if ( order 1 )
bubble( a, arraySize, ascending ) cout ltlt
"\nData items in ascending order\n" else
bubble( a, arraySize, descending )
cout ltlt "\nData items in descending order\n"
bool ascending( int a, int b ) return b
lt a // swap if b is less than a bool
descending( int a, int b ) return b gt a //
swap if b is greater than a
13
Array of Pointers to Functions
  • include ltiostreamgt
  • using stdcoutusing stdcinusing stdendl
  • void function1( int )
  • void function2( int )
  • void function3( int )
  • int main()
  • void (f 3 )( int ) function1,
    function2, function3
  • int choice
  • cout ltlt "Enter a number between 0 and 2, 3 to
    end "
  • cin gtgt choice
  • while ( choice gt 0 choice lt 3 )
  • (f choice )( choice )
  • cout ltlt "Enter a number between 0 and 2, 3
    to end "
  • cin gtgt choice
  • cout ltlt "Program execution completed." ltlt
    endl
  • return 0

f is an array of 3 pointers to functions (f1..f3)
that each take an int as an argument and return
void.
Menu Driven !!!
Function call, fchoice selects the pointer at
location choice, dereferences it, and (choice)
is passed as an arg to the fn..
14
Array of Pointers to Functions
  • continued . . . . .
  • void function1( int a )
  • cout ltlt "You entered " ltlt a
  • ltlt " so function1 was called\n\n"
  • void function2( int b )
  • cout ltlt "You entered " ltlt b
  • ltlt " so function2 was called\n\n"
  • void function3( int c )
  • cout ltlt "You entered " ltlt c
  • ltlt " so function3 was called\n\n"

15
Array of Pointers to Functions

16
C Dynamic Memory Allocation
// Program to illustrate dynamic memory
allocation Kelly 9.10 include ltiostreamgt using
namespace std void main() int int_array int
no_els,i cout ltlt "Enter the number of
elements" cin gtgt no_els // Allocate the memory
while the program is running int_array new
intno_els // Enter the elements into the
array for ( i0 iltno_els i ) cout
ltlt Enter element ltlt I ltlt cin gtgt
int_arrayi / Display the array values
just entered / for ( i0 iltno_els i )
cout "Element ltlt I ltlt is ltlt (int_arrayi) ltlt
endl delete int_array // free the
allocated memory
New allocates the the exact number of elements
required, Delete frees the memory !!!
New invokes the constructor and delete invokes
the destructor
17
C Dynamic Memory Allocation
/ Program to illustrate dynamic memory
allocation using malloc()./ include
ltstdio.hgtinclude ltstdlib.hgt main() int
int_array int no_els,no_bytes,i printf(
"Enter the number of elements " ) scanf(
"d",no_els ) / Calculate the number of bytes
required by array / no_bytes no_els
sizeof(int) / Allocate the memory / int_array
(int ) malloc( no_bytes ) if ( int_array
NULL ) printf( "cannot allocate memory" )
else / Enter the elements into the array
/ for ( i0 iltno_els i ) printf(
"Enter element d ",i ) scanf(
"d",int_arrayi ) / Display the array
values just entered / for ( i0 iltno_els i
) printf( "Element d is d\n",i,(int_arrayi
) ) free( int_array ) / free the allocated
memory /
In ANSI C, to dynamically create an object of
type TypeName, you would say typeNamePtr
malloc( sizeof( TypeName ) )This requires a
function call to malloc and explicit use of the
sizeof operator. Function malloc does not provide
any method of initializing the allocated block of
memory.
Write a Comment
User Comments (0)
About PowerShow.com