This is a simple question, but, when I am using the strstr function, why does the size of the needle have to be at least one character bigger than the actual text in the needle? Is this because of the null character?
When I put the needle as needle[1], it does not work. Why is it fine to put the exact number of characters for the haystack?
#include <stdio.h>
#include <string.h>
int main(void)
{
const char haystack[21] = "IDontUnderstand?Help!";
const char needle[2] = "?";
char *buffer;
buffer = strstr(haystack, needle);
printf("The substring is: %s\n", buffer);
return(0);
}
In theory, both strings should have the null terminating character at the end ('\0
) because the function otherwise does not know when to stop reading the string:
Take the strlen
function. It reads the length of the string up to the null character and can be implemented like so:
size_t strlen(const char* str)
{
size_t len = 0;
for(; *str; ++str, ++len);
return (len);
}
Note the condition is *str
, which also can mean *str != 0
, which shows that the for loop increments the string and length until a null character is found.
However, if a null terminator is not given (e.g. you allocated char[5]
for "Hello"
, when it should actually be char[6]
- "Hello\0"
), it is pure luck if the function you use stops at the end of "hello".
To make it easier, if you are writing a character array, you could instead not include the number in the braces and allow the compiler to deduce it for you to ensure that there is a null terminating character:
const char haystack[] = "IDontUnderstand?Help!";
const char needle[] = "?";
Note that you cannot put const char haystack[strlen("IDontUnderstand?Help!") + 1] = "IDontUnderstand?Help!";
as strlen("IDontUnderstand?Help!") + 1
is not a constant value.
However, if you want to dynamically allocate the memory, you can use the strlen
to help:
char* get_str_buffer(const char* value)
{
char* buf = malloc(strlen(value) + 1);
strcpy(buf, value);
return (buf);
}
int main(void)
{
const char *haystack = get_str_buffer("IDontUnderstand?Help!");
const char *needle = get_str_buffer("?");
char *buffer;
buffer = strstr(haystack, needle);
printf("The substring is: %s\n", buffer);
free(haystack);
free(needle);
return(0);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments