To copy strings in C, you can use strcpy. Here is an example:
#include <stdio.h>
#include <string.h>
const char * my_str = "Content";
char * my_copy;
my_copy = malloc(sizeof(char) * (strlen(my_str) + 1));
strcpy(my_copy,my_str);
If you want to avoid accidental buffer overflows, use strncpy instead of strcpy. For example:
const char * my_str = "Content";
const size_t len_my_str = strlen(my_str) + 1;
char * my_copy = malloc(len_my_str);
strncpy(my_copy, my_str, len_my_str);
Answer from Vitor Villar on Stack OverflowTo copy strings in C, you can use strcpy. Here is an example:
#include <stdio.h>
#include <string.h>
const char * my_str = "Content";
char * my_copy;
my_copy = malloc(sizeof(char) * (strlen(my_str) + 1));
strcpy(my_copy,my_str);
If you want to avoid accidental buffer overflows, use strncpy instead of strcpy. For example:
const char * my_str = "Content";
const size_t len_my_str = strlen(my_str) + 1;
char * my_copy = malloc(len_my_str);
strncpy(my_copy, my_str, len_my_str);
To perform such manual copy:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* orig_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char* ptr = orig_str;
// Memory layout for orig_str:
// ------------------------------------------------------------------------
// |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26| --> indices
// ------------------------------------------------------------------------
// |A|B|C|D|E|F|G|H|I|J|K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z |\0| --> data
// ------------------------------------------------------------------------
int orig_str_size = 0;
char* bkup_copy = NULL;
// Count the number of characters in the original string
while (*ptr++ != '\0')
orig_str_size++;
printf("Size of the original string: %d\n", orig_str_size);
/* Dynamically allocate space for the backup copy */
// Why orig_str_size plus 1? We add +1 to account for the mandatory
// '\0' at the end of the string.
bkup_copy = (char*) malloc((orig_str_size+1) * sizeof(char));
// Place the '\0' character at the end of the backup string.
bkup_copy[orig_str_size] = '\0';
// Current memory layout for bkup_copy:
// ------------------------------------------------------------------------
// |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26| --> indices
// ------------------------------------------------------------------------
// | | | | | | | | | | | | | | | | | | | | | | | | | | |\0| --> data
// ------------------------------------------------------------------------
/* Finally, copy the characters from one string to the other */
// Remember to reset the helper pointer so it points to the beginning
// of the original string!
ptr = &orig_str[0];
int idx = 0;
while (*ptr != '\0')
bkup_copy[idx++] = *ptr++;
printf("Original String: %s\n", orig_str);
printf("Backup String: %s\n", bkup_copy);
return 0;
}
Videos
A C string is a nul-terminated character array.
The C language does not allow assigning the contents of an array to another
array. As noted by Barry, you must copy the individual characters one by one
from the source array to the destination array. e.g. -
#define _CRT_SECURE_NO_WARNINGS
#include
#include
int main()
{
char str1[] = "Hello";
char str2[10] = {0};
for (int x = 0; x < strlen(str1); ++x)
{
str2[x] = str1[x];
}
printf("%s\n", str2);
return 0;
}
To make this common task easier there are standard library functions provided
which will perform this operation. e.g. - memcpy(), etc.
memcpy(str2, str1, 6);
When the array contains a nul-terminated string of characters you can use
strcpy(), etc.
strcpy(str2, str1);
Caveat: Some of the above functions are considered unsafe as they do not guard
against buffer overruns of the source and destination arrays. There are safer
versions provided by the compiler.
Note that if and when you start learning C++ you will find that there you can
assign a C++ std::string object to another object of the same type. However,
even in C++ the same rules apply when working with C strings, "raw" character
arrays, etc.
- Wayne
str2 is an array. It cannot appear on the left side of an assignment. You will need to use something like strcpy.
q is a pointer. It is perfectly legal to copy one pointer to another.
void function (const char *string)
{
char *stringcopy = malloc (1 + strlen (string));
if (stringcopy)
strcpy (stringcopy, string);
else fprintf (stderr, "malloc failure!"):
...
do whatever needs to be done with `stringcopy`
}
To duplicate strings in C there is a library function called strdup made for that:
The memory allocated by strdup must be freed after usage using free.
strdup provides the memory allocation and string copy operation in one step. Using an char array can become problematic if at some point in time the string to copy happens to be larger than the array's size.
Your problem is with the destination of your copy: it's a char* that has not been initialized. When you try copying a C string into it, you get undefined behavior.
You need to initialize the pointer
char *to = malloc(100);
or make it an array of characters instead:
char to[100];
If you decide to go with malloc, you need to call free(to) once you are done with the copied string.
You need to allocate memory for to. Something like:
char *to = malloc(strlen(from) + 1);
Don't forget to free the allocated memory with a free(to) call when it is no longer needed.
By default, scanf stops reading the standard input stream when a space character ' ' is encountered. To fix it, you can use a scanset.
scanf("%[^\n]", first);
scanf() stops reading after the first whitespace by default. Use fgets() or gets()[unsafe]. With regards to why it is this way, you might want to read the POSIX pages here: http://www.unix.com/man-page/POSIX/3posix/scanf/ and ISO C standards here: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf. It has a lengthy description on how scanf() and fscanf()(and all other standard C functions) should work. These are generally followed guidelines on how functions in C library should work.
All compilers strive hard to create POSIX compliant standard-c libraries that work the same across most UNIX'ish platforms.
The standard C functions are actually defined here: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf