instructions: Rewrite Example 7.3 so that it uses direct pointer reference -- rather than array indexing.
approach 1:
1 2 3 4 5 6 7 8 9
void convertToUpper(char *s){
int length = strlen(s);
int i = 0;
while (*s < length + 1)
*s = toupper(s[i]);
*s++;
i++;
}
approach 2:
1 2 3 4 5 6 7 8 9 10 11
void convertToUpper(char *s){
int length = strlen(s);
int i = 0;
while (*s++)
if (*s == '\0')
break;
else
*s = toupper(s[i]);
i++;
}
my second approach almost works but the first letter is never capitalized ?.?
oh, this is the original example:
1 2 3 4 5 6
void convertToUpper(char *s){
int length = strlen(s);
for (int i = 0; i < length; i++)
s[i] = toupper(s[i]);
}
edit: ii added *s = toupper(s[i]); right before the while loop ii used in approach 2 and it worked. im guessing because the condition of the while loop is s++ it starts the loop at s[1] instead of s[0] ?
void convertToUpper(char *s){
int i = 0;
while (true)//*s++ doesn't ever exit and increments the value.
if (*s == '\0')
break;
else
{ // You need these to put two statements in the else
s[i] = toupper(s[i]); // *s should be s[i]
i++; //This was not even in the while before
}
}
Or
1 2 3 4 5 6 7
void convertToUpper(char *s){
while (s++)// increment the pointer, not the value
if (*s == '\0')
break;
else
s[0] = toupper(s[0]); // don't need i, always use 0.
}