-1

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!

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Nina06
  • 3
  • 3

3 Answers3

2

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;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Hi! Thanks for your answer. I have to delete the \0 cause i have to tokenize the string, and the \0 give me a lot of problem with the last token. But it doesn't work in this way.. – Nina06 Jul 28 '16 at 15:52
  • @Nina06 Then the tokenizer must be wrong because strings in C are represented as arrays of characters with terminating null-character. – MikeCAT Jul 28 '16 at 15:55
  • @Nina06 Or do you mean literally two characters \ and 0 by `\0`, not a character whose character code is 0? – MikeCAT Jul 28 '16 at 15:56
  • 1
    Well I suppose it's \0... in reality it's enter: \n – Nina06 Jul 28 '16 at 16:02
  • `char* lf; if ((lf = strchr(string, '\n')) != NULL) *lf = '\0';` This is what I use to remove the newline character. – MikeCAT Jul 28 '16 at 16:05
0

TL;DR You don't want null-terminator, fine. Along with that you should be ready to give up those properties, which comes with the presence of null-terminator. You can no longer make use of the array as string.


To elaborate, in your code, your array array is not null-terminated, so it cannot be used as a string. the %s format specifier expects a pointer to the null-terminated char array (in short, a string)

So, in your code,

printf("%s", array);

invokes undefined behavior by going past the allocated memory in search of the null-terminator.

You can however, print it element by element using a for loop.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

To copy without the terminating null, use memcpy( myCharArray, string, strlen(string) ); (assumes size of myCharArray is sucfficient). To print out the result, you need to use a loop instead of printf.

FredK
  • 4,094
  • 1
  • 9
  • 11