Write the function my_strncpy(). The function has three parameters: a char * dest, a const char * src, and an int max, which represents the maximum size of the destination buffer. Copy the characters in src to dest, but don't copy more than max-1 characters. Make sure you correctly terminate the copied string. The function returns a pointer to the first character in dest.
Is the for loop I used to empty the string correct?
And will the while loop copy the chars in src to dest?
I ran the code with some tests string, but it didn't gave me what I wanted.
char * my_strncpy(char * dest, const char * src, int max)
{
int b = 0;
for(int i = 0; i < max; i++)
{
dest[i] = '\0';
}
while(b < (max-2))
{
*dest = *src;
src++;
dest++;
b++;
}
return dest;
}
int main()
{
char cstr[50] = "Abadabadoo!";
char buf[10];
char * cat = "cat";
cout << "\nmy_strncpy(buf, cstr, 10) expects \"Abadabado\"" << endl;
cout << " -- \"" << my_strncpy(buf, cstr, sizeof(buf)) << "\"" << endl;
cout << "my_strncpy(buf, cat, 10) expects \"cat\"" << endl;
cout << " -- \"" << my_strncpy(buf, cat, sizeof(buf)) << "\"" << endl;
}