Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 51

Mandalay Technological University

Department of Electronic Engineering

EcE-22014 Technical Programming II

C Pointers
Chapter 7

Daw Khaing Zar Zar Myint


Lecturer
DEPARTMENT OF
ELECTRONIC
Outline ENGINEERING

7.1 Introduction
7.2 Pointer Variable Definitions and Initialization
7.3 Pointer Operators
7.4 Passing Arguments to Functions by Reference
7.5 Using the const Qualifier with Pointers
7.6 Bubble Sort Using Call-by-Reference
7.7 Size of Operator
7.8 Pointer Expressions and Pointer Arithmetic
7.9 Relationship between Pointers and Arrays
7.10 Arrays of Pointers

11/23/2023 Daw Khaing Zar Zar Myint 2


DEPARTMENT OF
ELECTRONIC
7.1 Introduction ENGINEERING

• Pointers are variables that holds address values


• The most powerful features of the C programming languages.
• Pointers enable programs to simulate call-by-reference and to
create and manipulate dynamic data structures.

11/23/2023 Daw Khaing Zar Zar Myint 3


DEPARTMENT OF
ELECTRONIC
7.2 Pointer Variable Definitions and ENGINEERING

Initialization

Pointers are variable whose values are memory addresses.


A pointer contains an address of a variable that contains a
specific value.
A pointer is constrained to point to a specific data type.
Eg, int, float, char

11/23/2023 Daw Khaing Zar Zar Myint 4


DEPARTMENT OF
ELECTRONIC
ENGINEERING

• A pointer is a symbolic representation of an address in the computer’s memory.


• The address operator =&
• The indirection operator =*

int*countPtr, count;

specifies that variable countPtr is of type int * (i.e., a pointer to an integer) and is
read, “countPtr is a pointer to int” or “countPtr points to an object of type int.”

11/23/2023 Daw Khaing Zar Zar Myint 5


DEPARTMENT OF
ELECTRONIC
Common Programming Error 7.1 ENGINEERING

The asterisk (*) notation used to declare pointer variables does not
distribute to all variable names in a declaration. Each pointer must be
declared with the * prefixed to the name; e.g., if you wish to declare xPtr
and yPtr as int pointers, use int *xPtr, *yPtr;.

Common Programming Error 7.2


Include the letters ptr in pointer variable names to make it clear that these
variables are pointers and thus need to be handled appropriately.

Error-Prevention Tip 7.1


Initialize pointers to prevent unexpected results.

11/23/2023 Daw Khaing Zar Zar Myint 6


DEPARTMENT OF
ELECTRONIC
7.3 Pointer Operators ENGINEERING

There are two pointers operations in C.


&- the address of operators when followed by a variable name,
& gives the address of that variable.
*- the dereferencing operator when followed by a pointer name
or an address, * gives the value stored at the pointed to address.

11/23/2023 Daw Khaing Zar Zar Myint 7


DEPARTMENT OF
ELECTRONIC
ENGINEERING

• & (address operator)


• Returns address of its operand
int y = 5;
int *yPtr;
yPtr = &y; /* yPtr gets address of y */

Fig. 7.2 | Graphical representation of a pointer Variable yPtr is said to “points to” y
pointing to an integer variable in memory.

8
DEPARTMENT OF
ELECTRONIC
ENGINEERING

Fig. 7.3 | Representation of y and yPtr in memory.

Assuming that integer variable y is stored at location 600000, and pointer


variable yPtr is stored at location 500000. The operand of the address operator
must be a variable; the address operator cannot be applied to constants, to
expressions or to variables declared with the storage class register.

9
DEPARTMENT OF
ELECTRONIC
Common Programming Error 7.3 ENGINEERING

Dereferencing a pointer that has not been properly initialized or


that has not been assigned to point to a specific location in
memory is an error. This could cause a fatal execution time error,
or it could accidentally modify important data and allow the
program to run to completion with incorrect results.

11/23/2023 Daw Khaing Zar Zar Myint 10


1 /* Fig. 7.4: fig07_04.c DEPARTMENT OF
2 Using the & and * operators */ ELECTRONIC
3 #include <stdio.h> ENGINEERING
4
5 int main( void )
6 {
7 int a; /* a is an integer */
8 int *aPtr; /* aPtr is a pointer to an integer */
9
10 a = 7;
11 aPtr = &a; /* aPtr set to address of a */
12
13 printf( "The address of a is %p"
14 "\nThe value of aPtr is %p", &a, aPtr );
15
16 printf( "\n\nThe value of a is %d"
17 "\nThe value of *aPtr is %d", a, *aPtr );
18
19 printf( "\n\nShowing that * and & are complements of "
20 "each other\n&*aPtr = %p"
21 "\n*&aPtr = %p\n", &*aPtr, *&aPtr );
22
23 return 0; /* indicates successful termination */
24
25 } /* end main */

11/23/2023 Daw Khaing Zar Zar Myint 11


DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 12


DEPARTMENT OF
ELECTRONIC
7.4 Passing Arguments to Functions by ENGINEERING

Reference
There are two ways to pass arguments to a function call-by-value
and call-by-reference. All arguments in C are passed by value.

11/23/2023 Daw Khaing Zar Zar Myint 13


DEPARTMENT OF
ELECTRONIC
ENGINEERING

• Call by Value
• Call by Reference
In call by value, original value cannot be
In call by reference, original value is changed or modified. In call by value, when you
changed or modified because we pass reference passed value to the function it is locally stored by the
(address). Here, address of the value is passed in the function parameter in stack memory location. If you
function, so actual and formal arguments shares the change the value of function parameter, it is changed
same address space. Hence, any value changed for the current function only but it not change the
inside the function, is reflected inside as well as value of variable inside the caller method such as
outside the function. main().
11/23/2023 Daw Khaing Zar Zar Myint 14
DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 15


1 /* Fig. 7.7: fig07_07.c DEPARTMENT OF
2 Cube a variable using call-by-reference with a pointer argument */ ELECTRONIC
3 ENGINEERING
4 #include <stdio.h>
5
6 void cubeByReference( int *nPtr ); /* prototype */
7
8 int main()
9 {
10 int number = 5; /* initialize number */
11
12 printf( "The original value of number is %d", number );
13
14 /* pass address of number to cubeByReference */
15 cubeByReference( &number );
16
17 printf( "\nThe new value of number is %d\n", number );
18
19 return 0; /* indicates successful termination */
20
21 } /* end main */
22
23 /* calculate cube of *nPtr; modifies variable number in main */
24 void cubeByReference( int *nPtr )
25 {
26 *nPtr = *nPtr * *nPtr * *nPtr; /* cube *nPtr */
27 } /* end function cubeByReference */

11/23/2023 Daw Khaing Zar Zar Myint 16


DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 17


DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 18


DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 19


DEPARTMENT OF
ELECTRONIC
Error-Prevention Tip 7.2 ENGINEERING

Use call-by-value to pass arguments to a function unless the caller


explicitly requires the called function to modify the value of the
argument variable in the caller’s environment. This prevents
accidental modification of the caller’s arguments and is another
example of the principle of least privilege.

11/23/2023 Daw Khaing Zar Zar Myint 20


DEPARTMENT OF
ELECTRONIC
7.5 Using the const Qualifier with Pointers ENGINEERING

Software Engineering Observation 7.1


The const qualifier can be used to enforce the principle of least privilege. Using the
principle of least privilege to properly design software reduces debugging time and
improper side effects, making a program easier to modify and maintain.
Portability Tip
7.1defined in Standard C, some compilers do not enforce it.
Although const is well

Error-Prevention Tip 7.3


If a variable does not (or should not) change in the body of a function to which it’s
passed, the variable should be declared const to ensure that it’s not accidentally
modified.

11/23/2023 Daw Khaing Zar Zar Myint 21


DEPARTMENT OF
ELECTRONIC
Software Engineering Observation 7.2 ENGINEERING

Only one value in a calling function can be altered when using call-by-value. That value
must be assigned from the return value of the function to a variable in the caller. To modify
multiple variables from a calling function in a called function, use call-by-reference.

Error-Prevention Tip 7.4


Before using a function, check its function prototype to determine
if the function is able to modify the values passed to it.

Common Programming Error


Being unaware7.4
that a function is expecting pointers as arguments for call-by-reference and
passing arguments call-by-value. Some compilers take the values assuming they’re pointers
and dereference the values as pointers. At runtime, memory-access violations or segmentation
faults are often generated. Other compilers catch the mismatch in types between arguments
and parameters and generate error messages.
11/23/2023 Daw Khaing Zar Zar Myint 22
DEPARTMENT OF
ELECTRONIC
ENGINEERING

There are four ways to pass a pointer to a function: a non-constant pointer


to non-constant data, a constant pointer to nonconstant data, a non-constant
pointer to constant data and a constant pointer to constant data.

11/23/2023 Daw Khaing Zar Zar Myint 23


DEPARTMENT OF
ELECTRONIC
Converting a String to Uppercase Using a ENGINEERING
Non-Constant Pointer to Non-Constant Data

Such a pointer might be used to receive a string as an argument to a function


that uses pointer arithmetic to process each character in the string.

The function processes the array string (pointed to by sPtr) one character at a
time using pointer arithmetic.

11/23/2023 Daw Khaing Zar Zar Myint 24


DEPARTMENT OF
ELECTRONIC
ENGINEERING

1 /* Fig. 7.10: fig07_10.c


2 Converting lowercase letters to uppercase letters
3 using a non-constant pointer to non-constant data */
4
5 #include <stdio.h>
6 #include <ctype.h>
7
8 void convertToUppercase( char *sPtr ); /* prototype */
9
10 int main( void )
11 {
12 char string[] = "characters and $32.98"; /* initialize char array */
13
14 printf( "The string before conversion is: %s", string );
15 convertToUppercase( string );
16 printf( "\nThe string after conversion is: %s\n", string );
17
18 return 0; /* indicates successful termination */
19
20 } /* end main */
21

11/23/2023 Daw Khaing Zar Zar Myint 25


DEPARTMENT OF
ELECTRONIC
ENGINEERING

22 /* convert string to uppercase letters */


23 void convertToUppercase( char *sPtr )
24 {
25 while ( *sPtr != '\0' ) { /* current character is not '\0' */
26
27 if ( islower( *sPtr ) ) { /* if character is lowercase, */
28 *sPtr = toupper( *sPtr ); /* convert to uppercase */
29 } /* end if */
30
31 ++sPtr; /* move sPtr to the next character */
32 } /* end while */
33
34 } /* end function convertToUppercase */

The string before conversion is: characters and $32.98


The string after conversion is: CHARACTERS AND $32.98

11/23/2023 Daw Khaing Zar Zar Myint 26


DEPARTMENT OF
ELECTRONIC
Printing a String One Character at a Time ENGINEERING
Using a Non-Constant Pointer to Non Constant
Data

A non-constant pointer to constant data can


be modified to point to any data item of the
appropriate type, but the data to which it
points cannot be modified.

11/23/2023 Daw Khaing Zar Zar Myint 27


DEPARTMENT OF
ELECTRONIC
Attempting to Modify a Constant Pointer to ENGINEERING
Non -Constant Data
A constant pointer to non-constant data always points to the same
memory location, and the data at that location can be modified
through the pointer.

11/23/2023 Daw Khaing Zar Zar Myint 28


DEPARTMENT OF
ELECTRONIC
Attempting to Modify a Constant Pointer to ENGINEERING
Constant Data
The least access privilege is granted by a constant pointer to
constant data. Such a pointer always points to the same memory
location, and the data at that memory location cannot be modified.

11/23/2023 Daw Khaing Zar Zar Myint 29


DEPARTMENT OF
ELECTRONIC
7.6 Bubble Sort Using Call-by-Reference ENGINEERING

• Implement bubble sort using pointers


• Swap two elements
• swap function must receive address (using &) of array
elements
• Array elements have call-by-value default
• Using pointers and the * operator, swap can switch array
elements
• Psuedocode
Initialize array
print data in original order
Call function bubble sort
print sorted array
Define bubble sort

11/23/2023 Daw Khaing Zar Zar Myint 30


1 /* Fig. 7.15: fig07_15.c
2 This program puts values into an array, sorts the values into
DEPARTMENT OF
3 ascending order, and prints the resulting array. */ ELECTRONIC
4 #include <stdio.h> ENGINEERING
5 #define SIZE 10
6
7 void bubbleSort( int * const array, const int size ); /* prototype */
8
9 int main( void )
10 {
11 /* initialize array a */
12 int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
13
14 int i; /* counter */
15
16 printf( "Data items in original order\n" );
17
18 /* loop through array a */
19 for ( i = 0; i < SIZE; i++ ) {
20 printf( "%4d", a[ i ] );
21 } /* end for */
22
23 bubbleSort( a, SIZE ); /* sort the array */
24
25 printf( "\nData items in ascending order\n" );
26
27 /* loop through array a */
28 for ( i = 0; i < SIZE; i++ ) {
29 printf( "%4d", a[ i ] );
30 } /* end for */
11/23/2023 Daw Khaing Zar Zar Myint 31
31
32 printf( "\n" );
DEPARTMENT OF
33 ELECTRONIC
34 return 0; /* indicates successful termination */ ENGINEERING
35
36 } /* end main */
37
38 /* sort an array of integers using bubble sort algorithm */
39 void bubbleSort( int * const array, const int size )
40 {
41 void swap( int *element1Ptr, int *element2Ptr ); /* prototype */
42 int pass; /* pass counter */
43 int j; /* comparison counter */
44
45 /* loop to control passes */
46 for ( pass = 0; pass < size - 1; pass++ ) {
47
48 /* loop to control comparisons during each pass */
49 for ( j = 0; j < size - 1; j++ ) {
50
51 /* swap adjacent elements if they are out of order */
52 if ( array[ j ] > array[ j + 1 ] ) {
53 swap( &array[ j ], &array[ j + 1 ] );
54 } /* end if */
55
56 } /* end inner for */
57
58 } /* end outer for */
59
60 } /* end function bubbleSort */

11/23/2023 Daw Khaing Zar Zar Myint 32


DEPARTMENT OF
61 ELECTRONIC
62 /* swap values at memory locations to which element1Ptr and ENGINEERING

63 element2Ptr point */
64 void swap( int *element1Ptr, int *element2Ptr )
65 {
66 int hold = *element1Ptr;
67 *element1Ptr = *element2Ptr;
68 *element2Ptr = hold;
69 } /* end function swap */

Data items in original order


2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45 68 89

11/23/2023 Daw Khaing Zar Zar Myint 33


DEPARTMENT OF
ELECTRONIC
Software Engineering Observation 7.3 ENGINEERING

Placing function prototypes in the definitions of other functions enforces the


principle of least privilege by restricting proper function calls to the functions in
which the prototypes appear.

Software Engineering Observation 7.4


When passing an array to a function, also pass the size of the array. This helps
make the function reusable in many programs.

Software Engineering Observation 7.5


Global variables usually violate the principle of least privilege and can lead to
poor software engineering. Global variables should be used only to represent
truly shared resources, such as the time of day.

11/23/2023 Daw Khaing Zar Zar Myint 34


DEPARTMENT OF
ELECTRONIC
7.7 Size of ENGINEERING

• sizeof
Operator
• Returns size of operand in bytes
• For arrays: size of 1 element * number of elements
• if sizeof( int ) equals 4 bytes, then
• int myArray[ 10 ];
• printf( "%d", sizeof( myArray ) );
• will print 40
• sizeof can be used with
• Variable names
• Type name
• Constant values
Performance Tip 7.2
Sizeof is a compile-time operator, so it does not incur any execution-time overhead.
11/23/2023 Daw Khaing Zar Zar Myint 35
DEPARTMENT OF
ELECTRONIC
Portability Tip 7.2 ENGINEERING

The number of bytes used to store a particular data type may vary
between systems. When writing programs that depend on data type
sizes and that will run on several computer systems, use sizeof to
determine the number of bytes used to store the data types.

11/23/2023 Daw Khaing Zar Zar Myint 36


DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 37


DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 38


DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 39


DEPARTMENT OF
ELECTRONIC
7.8 Pointer Expressions and Pointer ENGINEERING

Arithmetic
Assume that array int v[5] has been defined and its first element is at
location 3000 in memory. Assume pointer vPtr has been initialized to point
to v[0]—i.e., the value of vPtr is 3000. Figure 7.18 illustrates this situation
for a machine with 4-byte integers. Variable vPtr can be initialized to point
to array v with either of the statements

vPtr = v;
vPtr =
&v[ 0 ];

11/23/2023 Daw Khaing Zar Zar Myint 40


DEPARTMENT OF
ELECTRONIC
Portability Tip 7.3 ENGINEERING

Most computers today have 2-byte or 4-byte integers. Some of the


newer machines use 8- byte integers. Because the results of pointer
arithmetic depend on the size of the objects a pointer points to,
pointer arithmetic is machine dependent.

vPtr += 2;

11/23/2023 Daw Khaing Zar Zar Myint 41


DEPARTMENT OF
ELECTRONIC
Common Programming Error 7.5 ENGINEERING

Using pointer arithmetic on a pointer that does not refer to an element in an array.

Common Programming Error 7.6


Subtracting or comparing two pointers that do not refer to elements in the same array.

Common Programming Error 7.7


Running off either end of an array when using pointer arithmetic.

Common Programming Error 7.8


Assigning a pointer of one type to a pointer of another type if neither is of type void * is
a syntax error.

Common Programming Error 7.9


Dereferencing a void * pointer is a syntax error.
11/23/2023 Daw Khaing Zar Zar Myint 42
DEPARTMENT OF
ELECTRONIC
7.9 Relationship between Pointers and Arrays ENGINEERING

bPtr = b;

bPtr = &b[ 0 ];

*( bPtr + 3 )
&b[ 3 ]

bPtr + 3

*( b + 3 )

11/23/2023 Daw Khaing Zar Zar Myint 43


DEPARTMENT OF
ELECTRONIC
ENGINEERING
Common Programming Error 7.10

Attempting to modify an array name with pointer arithmetic is a syntax error.

11/23/2023 Daw Khaing Zar Zar Myint 44


DEPARTMENT OF
ELECTRONIC
7.10 Arrays to ENGINEERING

Pointers
Arrays may contain pointers. A common use of an array of pointers is to form
an array of strings, referred to simply as a string array.

const char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs",


"Spades" };

11/23/2023 Daw Khaing Zar Zar Myint 45


DEPARTMENT OF
ELECTRONIC
Guess ! Head or Tail of a ENGINEERING

Coin

11/23/2023 Daw Khaing Zar Zar Myint 46


DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 47


DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 48


DEPARTMENT OF
ELECTRONIC
Guess ! Number ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 49


DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 50


DEPARTMENT OF
ELECTRONIC
ENGINEERING

11/23/2023 Daw Khaing Zar Zar Myint 51

You might also like