0

This is a program that delete spaces in the beginning and the end of a string c, can you tell me please where is the error in it ? I already tried running it in the debuger. It seems that the while loops aren't executed, kind of neglecting.

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
void main()
{
    char c[1000],d[1000];
    gets(c);
    int i=0,j=strlen(c)-1;
    while (c[i]==" ")
    {
        i++;
    }
    while (c[j]==" ")
    {
        j--;
    }
    int k,l=0;
    for (k=i;k<=j;k++)
    {
        d[l]=c[k];
        l++;
    }
    printf(d);
}
Youness
  • 11
  • 3
  • 1
    Aside: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – kaylum Nov 03 '21 at 23:02
  • Welcome to the site and thanks for including your full code. In the future, it would be better to simplify it a little more to create an [mcve]. (You can simplify it by removing the call to `gets` and just using a fixed string.) Then post the expected output and the actual output. – David Grayson Nov 03 '21 at 23:06
  • you seem to have arrived to the conclusion that the debugger is bugged. It's not. And that should be your last thought. If the debugger shows you that the while loops aren't entered then that means that your while loops aren't entered and you should focus your attention on the while condition. You have an invaluable tool and when that tools tells you what is wrong you question the tool instead of your code. – bolov Nov 03 '21 at 23:13

1 Answers1

1

You should use single quotes to get a space character in C. If you use double quotes, you get a pointer to a string containing a space character and a null terminator, which is different.

So change " " to ' '.

Your compiler should have warned you about this, since you are comparing a char to a const char *. Indeed, when I compile your code in gcc with the default options, it says:

test.c: In function 'main':
test.c:10:16: warning: comparison between pointer and integer
   10 |     while (c[i]==" ")
      |                ^~
test.c:14:16: warning: comparison between pointer and integer
   14 |     while (c[j]==" ")
      |                ^~

Your programming journey will be much easier if you pay attention to compiler warnings and fix them. You can also pass options like -Wall to your compiler to make it give you more warnings.

Also you need to add a null terminator to your d string. So add this line after the last loop:

d[l] = 0;
David Grayson
  • 84,103
  • 24
  • 152
  • 189