I have a string literal:
char *tmp = "xxxx";
I want to copy the string literal into an array.
For example:
how do I copy tmp
into an char array[50]
?
and how to copy one string literal to another?
Use strcpy()
, strncpy()
, strlcpy()
or memcpy()
, according to your specific needs.
With the following variables:
const char *tmp = "xxxx";
char buffer[50];
You typically need to ensure your string will be null terminated after copying:
memset(buffer, 0, sizeof buffer);
strncpy(buffer, tmp, sizeof buffer - 1);
An alternative approach:
strncpy(buffer, tmp, sizeof buffer);
buffer[sizeof buffer - 1] = '\0';
Some systems also provide strlcpy()
which handles the NUL byte correctly:
strlcpy(buffer, tmp, sizeof buffer);
You could naively implement strlcpy()
yourself as follows:
size_t strlcpy(char *dest, const char *src, size_t n)
{
size_t len = strlen(src);
if (len < n)
memcpy(dest, src, len + 1);
else {
memcpy(dest, src, n - 1);
dest[n - 1] = '\0';
}
return len;
}
The above code also serves as an example for memcpy()
.
Finally, when you already know that the string will fit:
strcpy(buffer, tmp);
Use strcpy
, it is pretty much well documented and easy to find:
const char* tmp = "xxxx";
// ...
char array[50];
// ...
strcpy(array, tmp);
But of course, you must make sure that the length of the string that you are copying is smaller than the size of the array. An alternative then is to use strncpy
, which gives you an upper limit of the bytes being copied. Here's another example:
const char* tmp = "xxxx";
char array[50];
// ...
array[49] = '\0';
strncpy(array, tmp, 49); // copy a maximum of 49 characters
If the string is greater than 49, the array will still have a well-formed string, because it is null-terminated. Of course, it will only have the first 49 characters of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With