Session 6

Page 1

Session 6

Pointers (Lab Guide)

Objectives At the end of this chapter, you will be able to:  Use Pointers  Use Pointers with Arrays The steps given in this session are detailed comprehensive and carefully thought through. This has been done so that the learning objectives are met and the understanding of the tool is complete. Please follow the steps carefully. Part I – For the first 1 Hour and 30 Minutes: 6.1

Pointers Pointer variables in C can hold the address of a variable of any basic data type. That is, pointers can be of integer or char data type. An integer pointer variable will hold the address of an integer variable. A character pointer will hold the address of a character variable.

6.1.1

Counting the number of vowels in a string using pointers Pointers can be used instead of subscripts to traverse through elements in an array. For example, a string pointer can be used to point to the starting memory address of a word. Hence such a pointer could be used to read the characters in that word. To demonstrate this, let us write a C program to count the number of vowels in a word using pointers. The steps are listed below: 1.

Declare a character pointer variable. The code will be, char *ptr;

2.

Declare a character array and accept value for the same. The code will be, char word[10]; printf(“\n Enter a word : “); scanf(“%s”,word);

3.

Assign the character pointer to the string. The code will be, ptr = &word[0]; The address of the first character of the character array, word, will be stored in the pointer variable, ptr. In other words, the pointer ptr will be point to the first character in the character array word.

Pointers

51


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.