-4

I am a beginner in C programming. I recently tried solving a simple problem to find the short form of a string. I can't understand why we are using *(ptr+i-1) in the program. What if I use only * (ptr+i). Can anyone please tell me how this works?

#include<stdio.h>
#include<string.h>
int main()
{
    char sent[100];
    char *ptr;
    printf("Enter a sentence : ");
    gets(sent);

    char len=strlen(sent);
    printf("%c",*sent);
    ptr=&sent;
    for(int i=1; i<len; i++)
    {
        if(*(ptr+i-1) == ' ')
        {
            printf(" %c",*(ptr+i));
        }
    }
    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Code_Ostrich
  • 55
  • 1
  • 1
  • 11

1 Answers1

2

"I can't understand why we are using *(ptr+i-1) in the program. What if I use only * (ptr+i). Can anyone please tell me how this works?"

for(int i=1; i<len; i++)
{
    if(*(ptr+i-1) == ' ')
    {
        printf(" %c",*(ptr+i));
    }
}

*(ptr+i-1) is important as i is starting by/ initialized to 1 not 0 regarding reading the string from its first character, not the second.

With *(ptr+i) you would read from the second character of the string instead.


Side note:

gets(sent); -> Don´t use gets(), it is deprecated:

Why is the gets function so dangerous that it should not be used?