0

I'm trying to remove empty spaces from a char with pointer.

 char * byte="a b c d"
 char * CopiedByte;
 for (;*byte;++byte)
   {
    if(*byte!=' ')
      *CopiedByte=*byte;


  }
 printf("%s",CopiedByte);

But i dont get anything in output

Dim
  • 1
  • 3
  • 3
    You have a pointer `CopiedByte`, but *where does it point?!* – Some programmer dude Aug 29 '18 at 09:24
  • 2
    Also, don't forget that `char` strings in are really called ***null-terminated** byte strings*. That *null-terminator* is really important for all functions handling strings. If you forget it then string functions will go out of bounds looking for it. – Some programmer dude Aug 29 '18 at 09:25
  • Please show a [MCVE]. – Jabberwocky Aug 29 '18 at 09:26
  • So which is the easiest way? To use char array instead pointer? – Dim Aug 29 '18 at 09:26
  • 2
    Lastly, you never change where `CopiedByte` points, so you will overwrite the same location over and over. – Some programmer dude Aug 29 '18 at 09:27
  • your code doesn't compile .... missing at least ";" at the end of the first line. – Tom's Aug 29 '18 at 09:30
  • @Dim _To use char array instead pointer?_: it doesn't matter it's very similar. But your problem is not about using pointers or arrays, it's about your code being wrong (see previous comments) and your code being incomplete. You need to provide a [mcve]. – Jabberwocky Aug 29 '18 at 09:30

1 Answers1

2

You have not allocated memory to CopiedByte and once you copy the char from byte to CopiedByte you need to increment the CopiedByte to point to next location. Important note: Once you copy all the data put the NULL terminator.

Memory allocated using malloc(dynamically) need to be freed otherwise there will be memory leaks.

 char * byte="a b c d";
 char * CopiedByte = malloc(strlen(byte) +1);
 int i=0;
 for (;*byte;++byte)
   {
    if(*byte!=' ')
    {
      CopiedByte[i]=*byte;
      i++;
    }
  }
  CopiedByte[i] = '\0';

 /* do your work*/

  free(CopiedByte);
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44