1
C Programming for
Engineers
Pointers
ICEN 360– Spring 2017
Prof. Dola Saha
2
Pointers
Ø Pointers are variables whose values are memory
addresses.
Ø A variable name directly references a value, and a pointer
indirectly references a value.
Ø Referencing a value through a pointer is called
indirection.
3
Declaring Pointers
Ø Pointers must be defined before they can be used.
Ø The definition
o int *countPtr, count;
specifies that variable countPtr is of type int * (i.e., a pointer
to an integer).
Ø The variable count is defined to be an int, not a pointer to an
int.
4
Initializing Pointers
Ø Pointers should be initialized when they’re defined or they
can be assigned a value.
Ø A pointer may be initialized to NULL, 0 or an address.
Ø A pointer with the value NULL points to nothing.
Ø NULL is a symbolic constant defined in the <stddef.h>
header (and several other headers, such as <stdio.h>).
Ø Initializing a pointer to 0 is equivalent to initializing a
pointer to NULL, but NULL is preferred.
Ø When 0 is assigned, it’s first converted to a pointer of the
appropriate type.
Ø The value 0 is the only integer value that can be assigned
directly to a pointer variable.
5
Pointer Operator
Ø The &, or address operator, is a unary operator that returns the
address of its operand.
Ø Example definition
o int y = 5;
int *yPtr;
the statement
o yPtr = &y;
assigns the address of the variable y to pointer variable yPtr.
Ø Variable yPtr is then said to “point to” y.
Graphical Representation
Memory Representation
6
Indirection (*) Operator
Ø The unary * operator, commonly referred to as the
indirection operator or dereferencing operator, returns
the value of the object to which its operand (i.e., a
pointer) points.
Ø Example:
o printf("%d", *yPtr);
prints the value of variable that yPtr is pointing to
In this case it is y, whose value is 5.
Ø Using * in this manner is called dereferencing a pointer.
7
Using & and *
8
Pass by value
9
Pass by reference – simulating with Pointer
10
Pass by value (1)
11
Pass by value (2)
12
Pass by value (3)
13
Pass by reference (1)
14
Pass by reference (2)
15
Determine Size of Data Types (1)
16
Determine Size of Data Types (2)
17
Pointer Arithmetic
Ø A pointer may be
§ incremented (++) or decremented (--),
§ an integer may be added to a pointer (+ or +=),
§ an integer may be subtracted from a pointer (- or -=)
§ one pointer may be subtracted from another—this last operation is
meaningful only when both pointers point to elements of the same array.
Ø When an integer n is added to or subtracted from a pointer
§ Pointer is incremented or decremented by that integer times the size of the
object to which the pointer refers.
vPtr+=2;
18
Pointer and Array
Ø Arrays and pointers are intimately related in C and often may be used
interchangeably.
Ø An array name can be thought of as a constant pointer.
Ø Pointers can be used to do any operation involving array indexing.
Ø Set bPtr equal to the address of the first element in array b with
the statement
§ bPtr = b;
Ø Address of the array’s first element:
§ bPtr = &b[0];
19
Pointer and Array
Ø Array element b[3] with pointer expression
§ *(bPtr + 3)
§ The 3 in the expression is the offset to the pointer.
Ø This notation is referred to as pointer/offset notation.
Ø Address of b[3] can be referenced as
§ &b[3]
§ (bPtr+3)
20
Access array elements by pointer (1)
21
Access array elements by pointer (2)
22
Classroom Assignment
Ø Write a function encrypt() and a function decrypt() to
change each of the characters in a string shift by a given
value.
Ø Sample output where the values are shifted by 5.
String given = This is confidential information
String encrypted = Ymnx%nx%htsknijsynfq%nsktwrfynts
String decrypted = This is confidential information
23
Pointer Notation with Arrays (1)
24
Pointer Notation with Arrays (2)
25
Pointer Notation with Arrays (3)
26
Array of Pointers
Ø Arrays may contain pointers
304 Chapter 7 C Pointers
string is essentially a pointer to its first character. So each entry in an array of strings is ac-
tually a pointer to the first character of a string. Consider the definition of string array
suit, which might be useful in representing a deck of cards.
The suit[4] portion of the definition indicates an array of 4 elements. The char * por-
tion of the declaration indicates that each element of array suit is of type “pointer to
char.” Qualifier const indicates that the strings pointed to by each element pointer will
not be modified. The four values to be placed in the array are "Hearts", "Diamonds",
"Clubs" and "Spades". Each is stored in memory as a null-terminated character string
that’s one character longer than the number of characters between quotes. The four strings
are 7, 9, 6 and 7 characters long, respectively. Although it appears as though these strings
are being placed in the suit array, only pointers are actually stored in the array
(Fig. 7.22). Each pointer points to the first character of its corresponding string. Thus,
even though the suit array is fixed in size, it provides access to character strings of any
length. This flexibility is one example of C’s powerful data-structuring capabilities.
const char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades"
};
suit[1]
suit[0]
'D' 'i' 'a' 'm' 'o' 'n' 'd' 's' '0'
'H' 'e' 'a' 'r' 't' 's' '0'
7.11 Case Study: Card Shuffling and Dealing Simulatio
We use 4-by-13 double-subscripted array deck to represent the deck of pla
(Fig. 7.23). The rows correspond to the suits—row 0 corresponds to hearts, row
monds, row 2 to clubs and row 3 to spades. The columns correspond to the fac
the cards—columns 0 through 9 correspond to ace through ten respectively, an
10 through 12 correspond to jack, queen and king. We shall load string array
character strings representing the four suits, and string array face with charac
representing the thirteen face values.
0 5
4
3
deck[2][12] represents the King of Clubs
Clubs King
2
1
1
2
0
3
Diamonds
Clubs
Hearts
Spades
6 7 9
8 10 11 12
Ace
Six
Five
Four
Three
Two
Seven
Eight
Ten
Nine
Jack
Queen
King
tion of the declaration indicates that each element of array suit is of type “pointer to
char.” Qualifier const indicates that the strings pointed to by each element pointer will
not be modified. The four values to be placed in the array are "Hearts", "Diamonds",
"Clubs" and "Spades". Each is stored in memory as a null-terminated character string
that’s one character longer than the number of characters between quotes. The four strings
are 7, 9, 6 and 7 characters long, respectively. Although it appears as though these strings
are being placed in the suit array, only pointers are actually stored in the array
(Fig. 7.22). Each pointer points to the first character of its corresponding string. Thus,
even though the suit array is fixed in size, it provides access to character strings of any
length. This flexibility is one example of C’s powerful data-structuring capabilities.
The suits could have been placed in a two-dimensional array, in which each row
would represent a suit and each column would represent a letter from a suit name. Such a
data structure would have to have a fixed number of columns per row, and that number
would have to be as large as the largest string. Therefore, considerable memory could be
wasted when storing a large number of strings of which most were shorter than the longest
string. We use string arrays to represent a deck of cards in the next section.
7.11 Case Study: Card Shuffling and Dealing Simulation
In this section, we use random number generation to develop a card shuffling and dealing
simulation program. This program can then be used to implement programs that play
specific card games. To reveal some subtle performance problems, we’ve intentionally used
Fig. 7.22 | Graphical representation of the suit array.
'S'
suit[3]
suit[2]
suit[1]
suit[0]
'p' 'a' 'd' 'e' 's' '0'
'C' 'l' 'u' 'b' 's' '0'
'D' 'i' 'a' 'm' 'o' 'n' 'd' 's' '0'
'H' 'e' 'a' 'r' 't' 's' '0'
27
Pointers to Functions
Ø A pointer to a function contains address of function in the
memory.
the pointer in the array is used to call the function.
Figure 7.28 provides a generic example of the mechanics of defining and using an
array of pointers to functions. We define three functions—function1, function2 and
function3—that each take an integer argument and return nothing. We store pointers to
these three functions in array f, which is defined in line 14.
1 // Fig. 7.28: fig07_28.c
2 // Demonstrating an array of pointers to functions.
3 #include <stdio.h>
4
5 // prototypes
6
7
8
9
10 int main( void )
11 {
12
13
14
15
16 size_t choice; // variable to hold user's choice
17
18 printf( "%s", "Enter a number between 0 and 2, 3 to end: " );
19 scanf( "%u", &choice );
20
21 // process user's choice
22 while ( choice >= 0 && choice < 3 ) {
23
24
25
void function1( int a );
void function2( int b );
void function3( int c );
// initialize array of 3 pointers to functions that each take an
// int argument and return void
void (*f[ 3 ])( int ) = { function1, function2, function3 };
// invoke function at location choice in array f and pass
// choice as an argument
Figure 7.28 provides a generic example of the mechanics of defining and using an
array of pointers to functions. We define three functions—function1, function2 and
function3—that each take an integer argument and return nothing. We store pointers to
these three functions in array f, which is defined in line 14.
1 // Fig. 7.28: fig07_28.c
2 // Demonstrating an array of pointers to functions.
3 #include <stdio.h>
4
5 // prototypes
6
7
8
9
10 int main( void )
11 {
12
13
14
15
16 size_t choice; // variable to hold user's choice
17
18 printf( "%s", "Enter a number between 0 and 2, 3 to end: " );
19 scanf( "%u", &choice );
20
21 // process user's choice
22 while ( choice >= 0 && choice < 3 ) {
23
24
25
26
void function1( int a );
void function2( int b );
void function3( int c );
// initialize array of 3 pointers to functions that each take an
// int argument and return void
void (*f[ 3 ])( int ) = { function1, function2, function3 };
// invoke function at location choice in array f and pass
// choice as an argument
(*f[ choice ])( choice );
3 #include <stdio.h>
4
5 // prototypes
6
7
8
9
0 int main( void )
1 {
2
3
4
5
6 size_t choice; // variable to hold user's choice
7
8 printf( "%s", "Enter a number between 0 and 2, 3 to end: " );
9 scanf( "%u", &choice );
0
1 // process user's choice
2 while ( choice >= 0 && choice < 3 ) {
3
4
5
6
7
8 printf( "%s", "Enter a number between 0 and 2, 3 to end: " );
9 scanf( "%u", &choice );
0 } // end while
1
2 puts( "Program execution completed." );
3 } // end main
void function1( int a );
void function2( int b );
void function3( int c );
// initialize array of 3 pointers to functions that each take an
// int argument and return void
void (*f[ 3 ])( int ) = { function1, function2, function3 };
// invoke function at location choice in array f and pass
// choice as an argument
(*f[ choice ])( choice );
28
Stack - Push and Pop with Pointers
399
7.5 • Array Arguments
FIGURE 7.13 Functions push and pop
1. void
2. push(char stack[], /* input/output - the stack */
3. char item, /* input - data being pushed onto the stack */
4. int *top, /* input/output - pointer to top of stack */
5. int max_size) /* input - maximum size of stack */
6. {
7. if (*top < max_size-1) {
8. ++(*top);
9. stack[*top] = item;
10. }
11. }
12.
13. char
14. pop(char stack[], /* input/output - the stack */
15. int *top) /* input/output - pointer to top of stack */
16. {
17. char item; /* value popped off the stack */
18.
19. if (*top >= 0) {
20. item = stack[*top];
21. --(*top);
22. } else {
23. item = STACK_EMPTY;
24. }
25.
26. return (item);
27. }
29
Calculate Execution Time
Ø #include <time.h>
Ø clock_t start, end;
Ø start = clock();
Ø // Write the code that needs to be timed
Ø end = clock();
Ø double time_taken = ((double)(end-start)) /
CLOCKS_PER_SEC;
Ø printf("The time taken for this program is %lfn",
time_taken);

pointer in c through addressing modes esntial in c

  • 1.
    1 C Programming for Engineers Pointers ICEN360– Spring 2017 Prof. Dola Saha
  • 2.
    2 Pointers Ø Pointers arevariables whose values are memory addresses. Ø A variable name directly references a value, and a pointer indirectly references a value. Ø Referencing a value through a pointer is called indirection.
  • 3.
    3 Declaring Pointers Ø Pointersmust be defined before they can be used. Ø The definition o int *countPtr, count; specifies that variable countPtr is of type int * (i.e., a pointer to an integer). Ø The variable count is defined to be an int, not a pointer to an int.
  • 4.
    4 Initializing Pointers Ø Pointersshould be initialized when they’re defined or they can be assigned a value. Ø A pointer may be initialized to NULL, 0 or an address. Ø A pointer with the value NULL points to nothing. Ø NULL is a symbolic constant defined in the <stddef.h> header (and several other headers, such as <stdio.h>). Ø Initializing a pointer to 0 is equivalent to initializing a pointer to NULL, but NULL is preferred. Ø When 0 is assigned, it’s first converted to a pointer of the appropriate type. Ø The value 0 is the only integer value that can be assigned directly to a pointer variable.
  • 5.
    5 Pointer Operator Ø The&, or address operator, is a unary operator that returns the address of its operand. Ø Example definition o int y = 5; int *yPtr; the statement o yPtr = &y; assigns the address of the variable y to pointer variable yPtr. Ø Variable yPtr is then said to “point to” y. Graphical Representation Memory Representation
  • 6.
    6 Indirection (*) Operator ØThe unary * operator, commonly referred to as the indirection operator or dereferencing operator, returns the value of the object to which its operand (i.e., a pointer) points. Ø Example: o printf("%d", *yPtr); prints the value of variable that yPtr is pointing to In this case it is y, whose value is 5. Ø Using * in this manner is called dereferencing a pointer.
  • 7.
  • 8.
  • 9.
    9 Pass by reference– simulating with Pointer
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
    15 Determine Size ofData Types (1)
  • 16.
    16 Determine Size ofData Types (2)
  • 17.
    17 Pointer Arithmetic Ø Apointer may be § incremented (++) or decremented (--), § an integer may be added to a pointer (+ or +=), § an integer may be subtracted from a pointer (- or -=) § one pointer may be subtracted from another—this last operation is meaningful only when both pointers point to elements of the same array. Ø When an integer n is added to or subtracted from a pointer § Pointer is incremented or decremented by that integer times the size of the object to which the pointer refers. vPtr+=2;
  • 18.
    18 Pointer and Array ØArrays and pointers are intimately related in C and often may be used interchangeably. Ø An array name can be thought of as a constant pointer. Ø Pointers can be used to do any operation involving array indexing. Ø Set bPtr equal to the address of the first element in array b with the statement § bPtr = b; Ø Address of the array’s first element: § bPtr = &b[0];
  • 19.
    19 Pointer and Array ØArray element b[3] with pointer expression § *(bPtr + 3) § The 3 in the expression is the offset to the pointer. Ø This notation is referred to as pointer/offset notation. Ø Address of b[3] can be referenced as § &b[3] § (bPtr+3)
  • 20.
  • 21.
  • 22.
    22 Classroom Assignment Ø Writea function encrypt() and a function decrypt() to change each of the characters in a string shift by a given value. Ø Sample output where the values are shifted by 5. String given = This is confidential information String encrypted = Ymnx%nx%htsknijsynfq%nsktwrfynts String decrypted = This is confidential information
  • 23.
  • 24.
  • 25.
  • 26.
    26 Array of Pointers ØArrays may contain pointers 304 Chapter 7 C Pointers string is essentially a pointer to its first character. So each entry in an array of strings is ac- tually a pointer to the first character of a string. Consider the definition of string array suit, which might be useful in representing a deck of cards. The suit[4] portion of the definition indicates an array of 4 elements. The char * por- tion of the declaration indicates that each element of array suit is of type “pointer to char.” Qualifier const indicates that the strings pointed to by each element pointer will not be modified. The four values to be placed in the array are "Hearts", "Diamonds", "Clubs" and "Spades". Each is stored in memory as a null-terminated character string that’s one character longer than the number of characters between quotes. The four strings are 7, 9, 6 and 7 characters long, respectively. Although it appears as though these strings are being placed in the suit array, only pointers are actually stored in the array (Fig. 7.22). Each pointer points to the first character of its corresponding string. Thus, even though the suit array is fixed in size, it provides access to character strings of any length. This flexibility is one example of C’s powerful data-structuring capabilities. const char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }; suit[1] suit[0] 'D' 'i' 'a' 'm' 'o' 'n' 'd' 's' '0' 'H' 'e' 'a' 'r' 't' 's' '0' 7.11 Case Study: Card Shuffling and Dealing Simulatio We use 4-by-13 double-subscripted array deck to represent the deck of pla (Fig. 7.23). The rows correspond to the suits—row 0 corresponds to hearts, row monds, row 2 to clubs and row 3 to spades. The columns correspond to the fac the cards—columns 0 through 9 correspond to ace through ten respectively, an 10 through 12 correspond to jack, queen and king. We shall load string array character strings representing the four suits, and string array face with charac representing the thirteen face values. 0 5 4 3 deck[2][12] represents the King of Clubs Clubs King 2 1 1 2 0 3 Diamonds Clubs Hearts Spades 6 7 9 8 10 11 12 Ace Six Five Four Three Two Seven Eight Ten Nine Jack Queen King tion of the declaration indicates that each element of array suit is of type “pointer to char.” Qualifier const indicates that the strings pointed to by each element pointer will not be modified. The four values to be placed in the array are "Hearts", "Diamonds", "Clubs" and "Spades". Each is stored in memory as a null-terminated character string that’s one character longer than the number of characters between quotes. The four strings are 7, 9, 6 and 7 characters long, respectively. Although it appears as though these strings are being placed in the suit array, only pointers are actually stored in the array (Fig. 7.22). Each pointer points to the first character of its corresponding string. Thus, even though the suit array is fixed in size, it provides access to character strings of any length. This flexibility is one example of C’s powerful data-structuring capabilities. The suits could have been placed in a two-dimensional array, in which each row would represent a suit and each column would represent a letter from a suit name. Such a data structure would have to have a fixed number of columns per row, and that number would have to be as large as the largest string. Therefore, considerable memory could be wasted when storing a large number of strings of which most were shorter than the longest string. We use string arrays to represent a deck of cards in the next section. 7.11 Case Study: Card Shuffling and Dealing Simulation In this section, we use random number generation to develop a card shuffling and dealing simulation program. This program can then be used to implement programs that play specific card games. To reveal some subtle performance problems, we’ve intentionally used Fig. 7.22 | Graphical representation of the suit array. 'S' suit[3] suit[2] suit[1] suit[0] 'p' 'a' 'd' 'e' 's' '0' 'C' 'l' 'u' 'b' 's' '0' 'D' 'i' 'a' 'm' 'o' 'n' 'd' 's' '0' 'H' 'e' 'a' 'r' 't' 's' '0'
  • 27.
    27 Pointers to Functions ØA pointer to a function contains address of function in the memory. the pointer in the array is used to call the function. Figure 7.28 provides a generic example of the mechanics of defining and using an array of pointers to functions. We define three functions—function1, function2 and function3—that each take an integer argument and return nothing. We store pointers to these three functions in array f, which is defined in line 14. 1 // Fig. 7.28: fig07_28.c 2 // Demonstrating an array of pointers to functions. 3 #include <stdio.h> 4 5 // prototypes 6 7 8 9 10 int main( void ) 11 { 12 13 14 15 16 size_t choice; // variable to hold user's choice 17 18 printf( "%s", "Enter a number between 0 and 2, 3 to end: " ); 19 scanf( "%u", &choice ); 20 21 // process user's choice 22 while ( choice >= 0 && choice < 3 ) { 23 24 25 void function1( int a ); void function2( int b ); void function3( int c ); // initialize array of 3 pointers to functions that each take an // int argument and return void void (*f[ 3 ])( int ) = { function1, function2, function3 }; // invoke function at location choice in array f and pass // choice as an argument Figure 7.28 provides a generic example of the mechanics of defining and using an array of pointers to functions. We define three functions—function1, function2 and function3—that each take an integer argument and return nothing. We store pointers to these three functions in array f, which is defined in line 14. 1 // Fig. 7.28: fig07_28.c 2 // Demonstrating an array of pointers to functions. 3 #include <stdio.h> 4 5 // prototypes 6 7 8 9 10 int main( void ) 11 { 12 13 14 15 16 size_t choice; // variable to hold user's choice 17 18 printf( "%s", "Enter a number between 0 and 2, 3 to end: " ); 19 scanf( "%u", &choice ); 20 21 // process user's choice 22 while ( choice >= 0 && choice < 3 ) { 23 24 25 26 void function1( int a ); void function2( int b ); void function3( int c ); // initialize array of 3 pointers to functions that each take an // int argument and return void void (*f[ 3 ])( int ) = { function1, function2, function3 }; // invoke function at location choice in array f and pass // choice as an argument (*f[ choice ])( choice ); 3 #include <stdio.h> 4 5 // prototypes 6 7 8 9 0 int main( void ) 1 { 2 3 4 5 6 size_t choice; // variable to hold user's choice 7 8 printf( "%s", "Enter a number between 0 and 2, 3 to end: " ); 9 scanf( "%u", &choice ); 0 1 // process user's choice 2 while ( choice >= 0 && choice < 3 ) { 3 4 5 6 7 8 printf( "%s", "Enter a number between 0 and 2, 3 to end: " ); 9 scanf( "%u", &choice ); 0 } // end while 1 2 puts( "Program execution completed." ); 3 } // end main void function1( int a ); void function2( int b ); void function3( int c ); // initialize array of 3 pointers to functions that each take an // int argument and return void void (*f[ 3 ])( int ) = { function1, function2, function3 }; // invoke function at location choice in array f and pass // choice as an argument (*f[ choice ])( choice );
  • 28.
    28 Stack - Pushand Pop with Pointers 399 7.5 • Array Arguments FIGURE 7.13 Functions push and pop 1. void 2. push(char stack[], /* input/output - the stack */ 3. char item, /* input - data being pushed onto the stack */ 4. int *top, /* input/output - pointer to top of stack */ 5. int max_size) /* input - maximum size of stack */ 6. { 7. if (*top < max_size-1) { 8. ++(*top); 9. stack[*top] = item; 10. } 11. } 12. 13. char 14. pop(char stack[], /* input/output - the stack */ 15. int *top) /* input/output - pointer to top of stack */ 16. { 17. char item; /* value popped off the stack */ 18. 19. if (*top >= 0) { 20. item = stack[*top]; 21. --(*top); 22. } else { 23. item = STACK_EMPTY; 24. } 25. 26. return (item); 27. }
  • 29.
    29 Calculate Execution Time Ø#include <time.h> Ø clock_t start, end; Ø start = clock(); Ø // Write the code that needs to be timed Ø end = clock(); Ø double time_taken = ((double)(end-start)) / CLOCKS_PER_SEC; Ø printf("The time taken for this program is %lfn", time_taken);