I am writing a program to convert the lower case sentence into upper case. I also want the length of the string. I am doing it by (both) arrays and pointers. The program is as follows:-
/* Program to convert the lower case sentence in upper case sentence and also calculate the length of the string */
#include<stdio.h>
main()
{
char fac='a'-'A',ch[20],*ptr,a[20];int i=0,count=0;
ptr=ch;
/* Changing case and printing length by using pointers */
printf("Enter the required string");
gets(ptr);
while(*ptr!='\0')
{
*ptr+=fac; // LINE #1
ptr++;
count++;
}
puts(ptr);
printf("%d",count);
/* Changing case by using arrays */
printf("Enter the required string");
gets(ch);
while(ch[i]!='\0')
{
ch[i]+=fac;
i++;
}
puts(ch);
return 0;
}
This program is working perfectly for printing the length ( in the pointer part ) and changing the case ( in the array part).The problem is case-conversion by pointers. I am under impression that LINE#1 increments the value stored at the pointer “ptr” by the required number ( 32 ). But nothing is happening on the screen. Why is this happening? Please help.
Look at your loop:
You’ve incremented
ptruntil its value is the address of the nul terminator! So all you’re printing is an empty string.Instead, store the initial value of
ptrsomewhere before the loop: