Reputation: 37
My C++ class is going over C-style strings and working with pointers. I'm to write a function that has three parameters: a char * s1, a const char * s2, and a size_t max, which represents that maximum size of the s1 buffer. I am to append the characters in s2 to the end of s1. The directions advise me to make sure there is only one '\0' at the end of the combined characters and I am not to go beyond the end of the buffer I'm asked to copy to. The function will return a pointer to the first character in s1.
I cannot use any functions in the standard library. What I can use are pointers, pointer arithmetic or array notation.
I've started, but not sure where to go.
const char * myFunction (char * s1, const char * s2, size_t max)
{
char * begin = s1;
while (*s1) s1++;
while ((s1 < begin + max - 1) && (*s2 != '\0')) {
*s1++ = *s2++;
}
return s1;
}
Not sure what to do after reaching the end of s1. How would I put s2 to the end of s1?
Upvotes: 1
Views: 273
Reputation: 12118
I cannot use any functions in the standard library.
The only required one would be strlen()
, I think. Roll your own:
#define min(a,b) ((a) < (b)) ? (a) : (b)
size_t str_length(const char* s)
{
size_t len = 0;
for( ; *s; ++s, ++len);
return len;
}
const char * append (char * s1, const char * s2, size_t max)
{
if(!s1 || !s2) //If either of strings is NULL, nothing to be done
return s1;
size_t s1_length = str_length(s1);
if(s1_length < max - 1) //If there is a room in s1...
{
size_t s2_length = str_length(s2); //Get length of s2
size_t append_size = min(s2_length, max - s1_length - 1); //Make sure we won't copy more than buffer can hold
if(append_size > 0)
{
memcpy(s1 + s1_length, s2, append_size); //This will overwrite null terminator in 's1'
s1[s1_length + append_size] = 0;
}
}
return s1;
}
Test:
int main(void)
{
char dest[64] = "This is a test";
append(dest, " of strings appending", 64);
printf("%s (length: %d)\n", dest, str_length(dest));
append(dest, " of appending too long string, that will probably not fit inside destination buffer", 64);
printf("%s (length: %d)\n", dest, str_length(dest));
return 0;
}
Output:
This is a test of strings appending (length: 35)
This is a test of strings appending of appending too long strin (length: 63)
Upvotes: 3