Search code examples
carraysstringfgetsnull-terminated

Copy a string into another without \0


I have to put a string into another without \0, I tryed a lot of ways but the string is always dirty.

char string[100];
int pos=0;

fgets(string, 99, stdin);
len = strlen(string);
printf("%d\n", len);
char array[len-1];

for(pos=0; pos<(len-1); pos++)
    {
      array[j]=string[pos];
      j++;
    }

printf("%s", string);
printf("%s", array);

In the terminal I have: dogs dogs(ENTER) 10(ENTER) dogs dogs(ENTER) dogs dogs@

I also tryed to remove \0 using another symbol but it can't see '\0' or '\n', help me plz!


Solution

  • Passing pointer to what is not a null-terminated string to %s without length specification will invoke undefined behavior. You have to specify the length to print if you hate terminating null-character for some reason.

    Try this:

    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
      int len;
    
      char string[100];
      int pos=0;
    
      fgets(string, 99, stdin);
      len = strlen(string);
      printf("%d\n", len);
      char array[len];
    
      for(pos=0; pos<len; pos++)
          {
            array[pos]=string[pos];
          }
    
      printf("%s", string);
      printf("%*s", len, array);
    
      return 0;
    }