If the length of the string you desire to copy is unknown, you can use snprintf
here. This function sends formatted output to str. It acts similarily to sprintf()
, but instead does not write more bytes allocated by str. If the resulting string is longer than n-1
characters, then the remaining characters are left out. It also always includes the null terminator
, unless the buffer size is 0
.
This would be a alternative to strncpy()
or strcpy()
, if you really don't want to use it. However, manually adding a null terminator at the end of your string with strcpy()
is always a simple, efficient approach. It is very normal in C to add a null terminator at the end of any processed string.
Here is a basic example of using sprintf()
:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 1024
int main(void) {
const size_t N = SIZE;
char str[N];
const char *example = "Hello World";
snprintf(str, sizeof(str), "%s", example);
printf("String = %s, Length = %zu
", str, strlen(str));
return 0;
}
Which prints out:
String = Hello World, Length = 11
This example shows that snprintf()
copied over "Hello World"
into str
, and also added a
terminator at the end.
Note: strlen()
only works on null terminated strings, and will cause undefined behaviour if the string is not null terminated. snprintf()
also needs more error checking, which can be found on the man page.
As others have said, this is not an efficient approach, but it is there if you go looking.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…