Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying string literals in C into an character array

Tags:

c

string

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?

like image 712
Anvita Potluri Avatar asked Sep 14 '14 22:09

Anvita Potluri


Video Answer


2 Answers

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);
like image 145
Pavel Šimerda Avatar answered Sep 19 '22 13:09

Pavel Šimerda


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.

like image 20
E_net4 stands with Ukraine Avatar answered Sep 19 '22 13:09

E_net4 stands with Ukraine