-3

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);
    }
}
Andrew Sun
  • 4,101
  • 6
  • 36
  • 53
  • 3
    Don't post code as image. – mx0 Nov 14 '18 at 17:14
  • Please don't post pictures of text but post text as text. Take the [tour] and read this: [ask] ans this: [mcve] – Jabberwocky Nov 14 '18 at 17:14
  • `for (*pt=0 ; *pt != '\0' ; *pt++)` --> `for ( ; pt; pt++)`. Also, use [`fgets`](https://linux.die.net/man/3/fgets) instead of `gets`, which is a security vulnerability. – yano Nov 14 '18 at 17:27
  • See [Why is the `gets()` function too dangerous to be used — ever!](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used) – Jonathan Leffler Nov 14 '18 at 17:39

2 Answers2

2

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++)
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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 ); ?

John Bode
  • 119,563
  • 19
  • 122
  • 198