简体   繁体   中英

Problem while printing string using Pointers in C Programming

Respected Experts ,

I am a newbie to C programming Language .

I am trying to print a string in C Language . The code runs successfully but when i enter the string , it does not displays the string entered by the user in return

I have attached the screenshot of the code which I am trying to execute .

Please help me out .

#include<stdio.h>

int main()
{
    char str[20];
    char *pt;

    printf("Enter any string :\n");
    gets(str);
    pt=&str[0];

    for(*pt=0; *pt != '\0'; *pt++)
    {
        printf("%c", *pt);
    }
}

The initialization *pt = 0; is causing the continuation test *pt != 0 to fail immediately, so your loop stops before printing anything.

You already initialized pt before the loop, so you don't need that step in the for() header. And you should be incrementing the pointer, not the character that it points so, so the update should be pt++ .

for (; *pt != '\0'; pt++) {
    printf("%c", *pt);
}

BTW, ptr = &str[0]; can be simplified to just ptr = str; . It's also more idiomatic to put this in the for header, so it would be:

for (pt = str; *pt != '\0'; pt++)

First - NEVER NEVER NEVER use gets , not even in toy code. It was deprecated in the 1999 standard and has been removed from the standard library as of the 2011 standard. It will introduce a point of failure / major security hole in your code. Use fgets instead, just be aware it will store the newline to your buffer if there's room.

Restructure your for statement as follows:

for ( pt = str; *pt != '\0'; pt++ )

The first expression sets pt to point to the first character in str (in this context, str is equivalent to &str[0] ). The second compares the value of the element that pt points to against the string terminator. Since you are trying to check the value of the pointed-to object, you must use the * operator to deference pt . The final expression advances pt to point to the next character in the string.

Finally, is there a reason you're printing the string out character by character instead of just writing printf( "%s\\n", str ); ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM