106 Intermediate C Programming
while ( str [ ind ] != ’0 ’)40
{41
i f ( str [ ind ] == ch )42
{43
return (& str [ ind ]) ;44
}45
ind ++;46
}47
// if the program reaches here , ch is not in str48
return NULL ;49
}50
The argument str stores the address of the first element of the input string. Since a
string is an array of characters, we treat str as an array, as shown at line 7. We can also
treat str as a pointer, as shown at lines 17, 19, 23, 30, 32, and 33. As you can see, lines 7, 17,
and 30 use the null terminator character, ’0’, to determine the end of the input strings.
Lines 17, 19, and 30 read the value at the address stored in str. This is the third usage of *
described in Table 4.1. Both lines read the value at that address. Line 23 increments str so
that it points to the next character in the array. Line 32 both reads from and writes to the
address. At the right side of =, it reads the value. At the left side of =, it writes the value.
Test your understanding of the program by answering this question: What happens
if lines 22 and 23 are exchanged (moving str ++; into the if condition right under
count ++;)? Is function my countchar still correct? Why?
7.1.7 Using const
The arguments of my countchar say that str is a constant. However, line 23 modifies
str. The seeming contradiction happens because const can be applied in two different
ways, with different meanings. The following example illustrates with two pointers chptr1
and chptr2:
// const .c1
#in clude < stdio .h >2
#in clude < stdlib .h >3
#in clude < string .h >4
int main ( i n t argc , char * argv [])5
{6
char str1 [20];7
char str2 [20];8
strcpy ( str1 , " First " );9
strcpy ( str2 , " Second ") ;10
const char * chptr1 = & str1 [0]; // const before char11
char * const chptr2 = & str1 [0]; // const after char12
// * chptr1 = ’C ’; // not allowed13
* chptr2 = ’C ’; // OK14
chptr1 = & str2 [0]; // OK15
// chptr2 = & str2 [0]; // not allowed16
return EXIT _SUCCES S ;17
}18
Both chptr1 and chptr2 are pointers and their values store the address of the first
element of str. The following shows the call stack. For simplicity, we do not show argc and
argv.