You can use strdup() to return a copy of the C-string, for example:
#include <string.h> const char *stringA = "foo"; char *stringB = NULL; stringB = strdup(stringA); /* ... */ free(stringB);
You can also use strcpy() , but first you need to allocate a place, which is not difficult to do, but can lead to an overflow error if it is not done correctly:
If you cannot use strdup() , I recommend using strncpy() instead of strcpy() . The strncpy() function copies up to - and only up to - n bytes, which helps to avoid overflow errors. However, if strlen(stringA) + 1 > n , you will need to end stringB yourself. But, as a rule, you will know what sizes you need for things:
I think strdup() cleaner, myself, so I try to use it when it works exclusively with strings. I donβt know if there are serious disadvantages for the POSIX / non-POSIX approach, in terms of performance, but I am not an expert in C or C ++.
Note that I passed the result of malloc() to char * . This is because your question is marked as a c++ question. In C ++, you need to pass the result from malloc() . In C, however, you did not select this.
EDIT
There you go, there is one complication: strdup() not in C or C ++. So use strcpy() or strncp() with a predefined array or malloc -ed pointer. It's a good habit to use strncp() instead of strcpy() , wherever you use this function. This will help reduce the likelihood of errors.
Alex reynolds
source share