Welcome to another exciting lesson on the C programming language! Today, we're going to dive deep into the strncpy() function, a handy tool in C's string handling arsenal. Let's get started! 🚀
The strncpy() function is used to copy a certain number of characters from a source string to a destination string in C. It's particularly useful when you want to limit the number of characters you're copying or when dealing with strings of varying lengths.
char *strncpy(char *dest, const char *src, size_t n);Parameters:
dest: Destination string where you want to copy the source string.src: Source string to be copied.n: Maximum number of characters to be copied.Let's see how strncpy() works with an example:
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello";
const char src[] = "World";
int len = strlen(src);
if (len > 19)
len = 19;
strncpy(dest, src, len);
dest[len] = '\0';
printf("Copied String: %s\n", dest);
return 0;
}Explanation:
dest and a source string src.strlen().strncpy() to copy the source string into the destination string, with a maximum of len characters.When you run this code, the output will be:
Copied String: World
strcpy(), strncpy() does not automatically append a null character at the end of the copied string. You must ensure that the destination string is null-terminated after copying.strncpy() is undefined, which means it might cause your program to crash or behave unexpectedly.Question: What happens if the number of characters to be copied using strncpy() exceeds the size of the destination array?
A: The program will continue to run without issues.
B: The program will crash.
C: The behavior is undefined.
Correct: C
Explanation: If the number of characters to be copied exceeds the size of the destination array, the behavior of strncpy() is undefined, which means it might cause your program to crash or behave unexpectedly.