Sie sind auf Seite 1von 29

TECHNOLOGICAL UNIVERSITY (MAUBIN)

DEPARTMENT OF ELECTRONIC ENGINEERING

EcE_22014, Technical Programming II


Chapter_7, C Pointers

By: Daw Moe Moe San


Assistant Lecturer
Outlines of Presentation
 Objectives
 Introduction
 Pointer Variable Definitions and Initialization
 Pointer Operators
 Passing Arguments to Functions
 Bubble Sort using Call-by-Reference
 sizeof Operator
 Relationship between Pointers and Arrays
 Pointers to Functions

2
Objectives
 To understand basic pointer concepts.
 To define and initialize pointer variables and operators.
 To use pointers to pass arguments to functions by reference.
 To study the close relationships among arrays, pointers and strings.
 To use pointers to functions.
 To define and use arrays of strings.

3
Introduction
 Pointers are among C’s most difficult capabilities to master..
 Pointers enable programs to simulate call-by-reference.
 Pointers can create and manipulate dynamic data structures..
Pointer Variable Definitions and Initialization
 Pointers, like all variables, must be define before they can be used.
 Pointers are variables whose values are memory addresses.
 A pointer contains an address of a variable that contains a specific value.
 A variable name directly references a value, and a pointer indirectly references a value.
 Referencing a value through a pointer is called indirection.
 Examples:
 int count; /* an integer variable count */
 int *countPtr; /* countPtr is a pointer to int or points to an object of type int*/
 Each pointer must be declared with the * prefixed to the name; e.g. int *xPtr; , int
*yPtr; . 4
Pointer Operators
 Use one-dimensional arrays to store and access list of data values.
c[ 5 ]
c[ 0 ] 7
c[ 1 ] 9
c[ 2 ] 5
c[ 3 ] 6
c[ 4 ] 2

 Examples:
 int c[ 5 ]; /* an integer array named c with size 5 */
 There are five elements in array c.
 All values are named c.
 The value of first element is c[ 0 ] = 7.
 The second value is c[ 1 ] = 9
 And, the value of fifth element, c[ 4 ] is 2.
5
Initializing Arrays
 Using for loop to initialize the elements of a 5-element integer array c to zero.

 First step, define array as follow:


int c [ 5 ];

 Then, initialize the array c:


for( i = 0; i < 5; i++ )
{ c [ i ] = 0; }
c[ 5 ]
i=0 c[ 0 ] = 0 c[ 0 ] 0
i=1 c[ 1 ] = 0 c[ 1 ] 0
i=2 c[ 2 ] = 0
i=3 c[ 3 ] = 0 c[ 2 ] 0
i=4 c[ 4 ] = 0 c[ 3 ] 0
c[ 4 ] 0

6
Cont;
 Using initializer list to initialize the elements of a 5-element integer
array c to zero.

 First step, define array as follow:


int c [ 5 ];

 Then, initialize the array c:


int c [ 5 ] = { 0 };

 Note:
 Arrays are not automatically initialized to zero.
 Must at least initialize the first element to zero for the remaining elements to be
automatically zeroed.

7
Cont;
 Example-1: Write a program that uses for loop to initialize the elements of a 10-element integer
array n to zeros and print the array in tabular format.

#include <stdio.h> /* Output contents of array n in tabular format*/


int main(void) printf( "%s%13s\n", "Element", "Value" );
{
int n[10]; /* n is an array of 10 integers */ for( i=0; i<10; i++ )
int i; /* counter */ {
printf( "%7d%13d\n", i, n[i] );
for( i=0; i<10; i++ ) } /* End for loop */
{
n[i] = 0; /* Set element at location i to 0 */ return 0;
} } /* End main */
8
Cont;
 Example-2: Write a program that initializes an integer array with 10 values using initializer list
and print the array in tabular format.

#include <stdio.h>
for( i=0; i<10; i++ )
int main(void)
{
{
printf( "%7d%13d\n", i, n[i] );
/* use initializer list to initialize array n */
} /* End for loop */
int n[10] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
int i; /* counter */
return 0;
} /* End main */
/* Output contents of array n in tabular format*/
printf( "%s%13s\n", "Element", "Value" );

9
Array Manipulations
 Example-3: Write a program that specify an array’s size with a symbolic constant
and initializes the10-element array s to the values 2, 4, 6, …, 20 with calculation
and print the array in tabular format.

#include <stdio.h> /* Output contents of array n in tabular format*/


#define SIZE 10 /* maximum size of array */ printf( "%s%13s\n", "Element", "Value" );
int main(void) for( i=0; i<SIZE; i++ )
{ {
/*symbolic constant SIZE can be used to specify array size*/ printf( "%7d%13d\n", i, s[i] );
int s[SIZE]; } /* End for loop */
int i; /* counter */
for( i=0; i<SIZE; i++ ) return 0;
{ s [ i ] = 2 + 2 * i; } /* Set the values */ } /* End main */
10
Cont;
 Example-4: Write a program that sums the values contained in the 12-elements integer array a
and print the total values.

#include <stdio.h> /* Output of total*/


#define SIZE 12 /* maximum size of array */ printf( “Total of array element values is %d\n”,
int main(void) total);
{ /* use initializer list to initialize array*/ return 0;
int a[SIZE]={1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, } /* End main */
45};
int i; /* counter */
int total=0; /* sum of array */

for( i=0; i<SIZE; i++ ) /*Sum contents of array a */


{ total += a [ i ]; } /* End for loop */
11
Cont;
 Example-5: Write a program to roll a single six-sided die 6000 times to test whether the random
number generator actually produces random numbers. (Using an array instead of switch)
#include <stdio.h> /* output frequency elements 1-6 in tabular format */
#include <stdlib.h>
printf( “%s%17s\n”, “Face”, “Frequency” );
#include <time.h>
#define SIZE 7 /* maximum size of array */ for( face=1; face < SIZE; face++ )
int main(void) {
{
printf( “%4d%17d\n”, face, frequency[ face ] );
int face;/* random die value 1-6 */
int roll; /* roll counter 1-6000 */ } /* End for loop */
int frequency[SIZE]={ 0 }; /* clear counts */ return 0;
srand( time( NULL ) ); /*seed random-number generator*/ } /* End main */

for( roll = 1; roll <= 6000; roll++ ) /* roll die 6000 times*/
{
face = 1 + rand( ) % 6;
++frequency[ face ];
}
12
Passion Arrays to Functions
 Pass by Reference
 C automatically passes (entire) arrays to functions by reference.
 The called functions can modify the element values .
 The name of array evaluates the address of the first element.

 Pass by Value
 C passes individual array elements to functions by value.
 The called functions can’t modify the element values.

 const Type Qualifier


 To prevent modification of array values in a function.
 const int a[ ];

13
Cont;
 Pass by Reference
#include<stdio.h> for( i = 0; i< SIZE; i++)
#define SIZE 5
void array( int b[ ], int size ); { printf("%3d", a[ i ] ); }
int main(void) return 0;
{ }
int a[SIZE] = { 0, 1, 2, 3, 4};
void array( int b[ ], int size )
int i;
{
printf("The values of the original array are:\n"); int j;
for( i = 0; i< SIZE; i++)
for( j=0; j <size; j++)
{ printf("%3d", a[ i ] ); }
{ b[ j ] *= 2; }
printf("\n"); }

array( a, SIZE );

printf("The values of the modified array are:\n");

14
Cont;
 Pass by Value
#include<stdio.h> void array( int e )
#define SIZE 5
void array( int e ); {
int main(void) printf("Modified element value is: %d\n", e *= 2);
{ }
int a[SIZE] = { 0, 1, 2, 3, 4};
int i;

printf("The values of the element a[ 3 ] is: %d\n", a[ 3 ]);

array( a[ 3 ]);

printf("The values of the modified element a[ 3 ] is: %d\n",


a[ 3 ]);

return 0;
}

15
Sorting Arrays
 One of the most important computing applications.
 Placing the data into a particular order such as ascending or descending.
 Bubble Sort or Sinking Sort
 For Ascending Order
 The smaller values upward to the top of the array like air bubbles rising in water.
 The larger values sink to the bottom of the array.
 Temporary location is used to swap array elements. (e.g. hold, temp, …)
2 hold
2
1
1 a[ 0 ] > a[ 1 ]
2 2
3 a[ 0 ] a[ 1 ]
1
3

16
Cont;
 Sorting the 10-element integer array into ascending order with bubble sort.
#include<stdio.h>
#define SIZE 10 if( a[ i ] > a[ i+1 ] )
int main( void ) {
{ hold = a[ i ];
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
a[ i ] = a[ i+1 ];
int pass; /* passes counter */
a[ i+1 ] = hold;
int i; /* comparisons counter */
} /* end if */
int hold; /* temporary location */
} /* end inner for */
printf("\nData items in original order\n"); } /* end outer for */
for( i = 0; i < SIZE; i++ )
{ printf("%4d", a[ i ]); } printf("\nData items in ascending order\n");
for( i = 0; i < SIZE; i++ )
for( pass = 1; pass < SIZE; pass++) { printf("%4d", a[ i ]); }
{ return 0;
for( i = 0; i < SIZE-1; i++) } /* end main */
{
17
Cont;
 Sorting the 10-element integer array into ascending order with bubble sort.

18
Searching Arrays
 Determine whether an array contains a value that matches a certain kay value.
 Finding a particular element of an array.

 Linear Search Technique


 The Linear Search compares each element of the array with search key.
 The technique works well for small or unsorted arrays.

 Binary Search Technique


 The array is sorted.
 The Binary Search eliminates from consideration one-half of the elements in a sorted array
after each comparison.

19
Cont;
 Searching an array with Linear Search.
0 2 4 6 8 10 12 14 16 18
int linearSearch(int a[ ], int key, int size)
{ a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
int n;
for( n = 0; n < size; n++ )
{ key=6
if( a[ n ] == key ) n=0

{ a[0] 0 0 != 6 n++

return n; n=1
} a[1] 2 2 != 6 n++

}
n=2
return -1; 4 != 6 n++
a[2] 4
}
n=3
a[3] 6 6 == 6 return 3
20
Cont;
 Searching an array with Linear Search.
#include<stdio.h> if( element != -1) for( n = 0; n < size; n++ )
#define SIZE 100 { {
int linearSearch(int array[ ], int key, int size); printf("Found value in element %d\n",
int main( void ) if( array[ n ] == key )
element);
{ {
}
int a[ SIZE ]; return n;
else
int x;
{ }
int searchKey;
int element; printf("Value not found\n"); }
for( x = 0; x < SIZE; x++ ) } return -1;
{ return 0;
}
a[ x ] = 2 * x; }
}
printf("\nEnter search key: "); int linearSearch(int array[ ], int key, int
scanf("%d", &searchKey); size)
{
element = linearSearch( a, searchKey, SIZE);
int n;
21
Cont;
 Searching an array with Binary Search.
#include<stdio.h> result = binarySearch( a, key, 0, SIZE-1 );
#define SIZE 15
int binarySearch( int b[ ], int searchKey, int low, int high); if( result != -1 )
int main( void ) {
{
printf("\n%d found in array element %d\n", key, result);
int a[ SIZE ];
}
int i;
else
int key;
int result; {
printf("\n%d not found\n", key);
for( i = 0; i < SIZE; i++) }
{
a[ i ] = 2 * i; return 0;
} }

printf("Enter a number between 0 and 28: ");


scanf("%d", &key);
22
Cont;
else
int binarySearch( int b[ ], int searchKey, int low, int high) {
{
low = middle +1;
int middle;
}
}
while( low <= high )
{
middle = ( low + high ) / 2; return -1;
}
if( searchKey == b[ middle ] )
{
return middle;
}
else if( searchKey < b[ middle ] )
{
high = middle - 1;
}

23
Cont;
int binarySearch( int b[ ], int searchKey, int low, int high) key=4
{
int middle; 0 2 4 6 8 10 12 14 16 18

while( low <= high ) b[0] b[1] b[2] b[3] b[4] b[5] b[6] b[7] b[8] b[9]
{
middle = ( low + high ) / 2; low=0
high=9
if( searchKey == b[ middle ] )
{ mid=(0+9)/2=4 b[4]=8 4 != 8
return middle;
} 4<8
else if( searchKey < b[ middle ] ) high=4-1=3
{
high = middle - 1; mid=(0+3)/2=1 b[1]=2 4 != 2
}
4<2
else { 4>2
low = middle +1; low=1+1=2
}
} mid=(2+3)/2=2 b[2]=4 4 == 4 return 2
return -1;
} 24
Multiple-Subscripted (Multidimensional) Arrays
 To represent the tables of values consisting of information arranged in rows and columns.
 To identify a particular table element, two subscripts are specified.
 The first identifies the element’s row and the second identifies the element’s column.
 Tables or arrays that required two subscripts to identify a particular element are called two
double-subscripted arrays.
 The m rows and n column array is called m-by-n array.
 For example: int c[ m ][ n ];
int c[ 3 ][ 4 ];
Table or array has 3 rows and 4 columns.

25
Cont;
 Initializing Multidimensional Arrays
#include<stdio.h> void printArray( int a[ ][ 3 ] )
void printArray( int a[ ][ 3 ] ); {
int main( void ) int i;
{ int j;
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6} };
for( i = 0; i <= 1; i++ )
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5, 6 };
{
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
for( j = 0; j <= 2; j++ )
printf("\nValue in array1 by row are:\n");
printArray( array1 ); {
printf("\t");
printf("\nValue in array2 by row are:\n"); printf( "%d", a[ i ][ j ] );
printArray( array2 ); }
printf("\n");
printf("\nValue in array3 by row are:\n"); }
printArray( array3 ); }
return 0;
}
26
Cont; Two-dimensional Array Manipulations (Average Grade)
#include<stdio.h>
#define STUDENTS 3
#define EXAMS 4
double average( const int setOfGrade[ ], int tests);
void printArray( const int grades[ ][ EXAMS ], int pupils, int tests);
int main( void )
{
int student;
const int studentGrades[ STUDENTS ][ EXAMS ] = { { 77, 68, 86, 73 }, { 96, 87, 89, 78}, { 70, 90,86, 81} };

printf("The array is: \n");


printArray( studentGrades, STUDENTS, EXAMS);
for( student = 0; student < students; student++ )
{
printf("the average grade for student %d is %.2f\n", student, average( studentgrades[ student ], exams) );
}
return 0;
}
27
Cont; Two-dimensional Array Manipulations
double average( const int setOfGrade[ ], int tests) for( j = 0; j < tests; j++ )
{ {
int i; printf("%-5d", grades[ i ][ j ]);
int total = 0; } /* end inner for */
for( i = 0; i < tests; i++ ) } /* end outer for */
{
total += setOfGrade[ i ]; printf("\n\n");
} } /* end function printArray */
return (double) total / tests;
}

void printArray( const int grades[ ][ EXAMS ], int pupils, int tests)
{
int i, j;
printf("%18c[0] [1] [2] [3]", ' '); /* output column head*/
for( i =0; i < pupils; i++ )
{
printf("\nstudentGrades[%d] ", i);
28
 
References:
Text Book, EcE_22014, Technical Programming II

How to Program, Sixth Edition By P.J.Deitel and H.M.Deitel, 2010.


(ISBN-10: 0-13-612356-2), (ISBN-13: 978-0-13-612356-9)

THANK YOU

29

Das könnte Ihnen auch gefallen