1

Should I always set the last value of a char array to '\0'?

char search_for[80];
search text here
printf("Search for: ");
scanf("%79s", search_for);
search_for[strlen(search_for) - 1] = '\0';

This is a example from a C book.

Marc.2377
  • 7,807
  • 7
  • 51
  • 95
K. Tomicki
  • 13
  • 3
  • 3
    If the `scanf` call didn't add the terminator, the call to `strlen` would not work. – Some programmer dude Oct 08 '18 at 07:44
  • 1
    Note: If `search_for[strlen(search_for) - 1] = '\0';` was indeed in some C book, it means that the book is not trustworthy learning material. This is too basic mistake to be acceptable in a serious book. – user694733 Oct 08 '18 at 07:51
  • The short answer is "only if you intend to use the contents of the array as a C-string". All functions that expect a string in C require the contents to the *nul-terminated*. If you are not using the contents as a string (meaning you won't try to print it using the `"%s"` format specifier, or won't pass the array to a string function such as `strcpy`, etc.., then there is no requirement. But if you want to use the contents as a *string*, then yes, it's a must. – David C. Rankin Oct 08 '18 at 08:16

1 Answers1

2

When using scanf with the %s format it adds it for you, one huge logical error you have though is using strlen when you're not sure that your string is null terminated.

nullp0tr
  • 485
  • 3
  • 11