Coderandhacker
Coderandhacker

Reputation: 135

Why empty output after processing pointer to string?

I have written the code that converts a string, entered by the user to lowercase, in two ways.

//method 1:
void xstrlwr(char*p)
{
    while(*p!='\0')
    {
        if(*p>=65&&*p<=90)
        {
            *p=*p+32;
        }
        p++;
    }
    printf("%s",p);
}

and

//method 2:
void xstrlwr(char*p)
{
    int l,i;
    l=strlen(p);
    for(i=0;i<=l;i++)
    {
        if(p[i]>=65&&p[i]<=90)
        {
            p[i]=p[i]+32;
        }
    }
    printf("\n%s",p);
}

here is the expected output

Input : WElcome TO sTack OverFLow
Expected output: welcome to stack overflow

the code 1 is not running correctly (printing the string has empty output),
whereas the code 2 is running perfectly (it outputs the lowercase string).
So my question is why the first one has empty output although both codes are logically identical, just having different notations?

Upvotes: 2

Views: 93

Answers (3)

EddingtonsMonkey
EddingtonsMonkey

Reputation: 142

Maybe this is just an exercise in playing with ASCII, but if not you should really be using tolower() instead of bit-banging. It's more portable.

EDIT: This would have been better as a comment, since it's more of an aside/observation than an answer to the question.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

Your printf in the first snippet is not printing anything since the pointer points to the NUL terminator. (Note the use of p++ in that snippet.)

In the second snippet you don't change the parameter passed to the function, so p still points to the start of the string.

The "guts" of both functions are identical although I prefer the first one. The moral of the story here is to print the results at the function calling site, not in the function itself.

Finally note that either algorithm only works for platforms using ASCII (or a close cousin) for character encoding. For this reason, the C standard library provides tolower to do this job.

Upvotes: 3

Ashwani
Ashwani

Reputation: 2052

both codes are logically same just having different notations?

That is not true. In method2 the pointer p never changed. At the end of the loop it still points to the start of the string. And in method1 after the end of the loop, p points to \0, the null terminator of the input string (because of p++). You can create a copy of p to fix it.

void xstrlwr(char*p)
{
    char *q = p;                // A copy
    while(*p!='\0')
    {
        if(*p>=65&&*p<=90)
        {
            *p=*p+32;
        }
        p++;
    }
    printf("%s",q);           // q not p
}

Upvotes: 2

Related Questions