Wenn Sie darauf bestehen, die strcpy
sollte Ihr Code leicht geändert werden:
int main() {
const char *f = "First";
const char *s = "Second";
char *tmp = malloc(strlen(f) + strlen(s) + 1);
strcpy(tmp, f);
strcpy(tmp+strlen(f), s);
printf("%s", tmp);
free(tmp);
return 0;
}
Sie sollten Folgendes in Betracht ziehen strncpy
代わりに strcpy
aus Sicherheitsgründen. Auch, strcat
ist eine konventionellere Funktion zur Verkettung von C-Strings.
EDIT Hier ist ein Beispiel für die Verwendung strncpy
代わりに strcpy
#define MAX 1024
int main() {
const char *f = "First";
const char *s = "Second";
size_t len_f = min(strlen(f), MAX);
size_t len_s = min(strlen(s), MAX);
size_t len_total = len_f + len_s;
char *tmp = malloc(len_total + 1);
strncpy(tmp, f, len_f);
strncpy(tmp+len_f, s, len_s);
tmp[len_total] = '\0';
printf("%s", tmp);
free(tmp);
return 0;
}