strcpy and strcat
- C course
- Beginner
- Lesson 62/116
- 5 min
Learn to copy with strcpy and concatenate with strcat.
Copying strings with strcpy
In C, you cannot copy strings later with =; you must use the strcpy function from <string.h>.
char src[] = "Hello";
char dst[20];
strcpy(dst, src);
/* dst: "Hello" */The destination array must be at least one element larger than the source string (for the null). Otherwise, overflow occurs and behavior becomes undefined.
Joining strings with strcat
strcat appends the source to the end of the destination. The destination array must be large enough to hold the result.
char greeting[20] = "Hello, ";
strcat(greeting, "Anna");
/* greeting: "Hello, Anna" */strcat finds the null in the destination, overwrites it, and places a new null at the end. If the destination is too small, overflow occurs; sizing matters.
Practice Join first and last name
Define char full[40] and copy "Anna" into it with strcpy. Then append " Smith" with strcat. Print with printf %s; output should be Anna Smith.
Starter code
#include <stdio.h>
#include <string.h>
int main(void) {
char full[40];
/* copy "Anna" with strcpy */
/* append " Smith" with strcat */
/* print with printf %s */
return 0;
}Sample solution
#include <stdio.h>
#include <string.h>
int main(void) {
char full[40];
strcpy(full, "Anna");
strcat(full, " Smith");
printf("%s\n", full);
return 0;
}Expected output
Anna Smith
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of these assignments causes a compile error?
- char a[] = "Hello";
- char b[20]; strcpy(b, a);
- char c[20] = a; Correct answer
- char d[] = {'A','l','i','\0'};
Explanation: You cannot copy between arrays with =; strcpy is needed.
2 strcpy call
strcpy(dst, ____); /* copy from src to dst */
strcpy(dst, src); /* copy from src to dst */
Explanation: The second argument is the source, the first is the destination.
3 Match strcpy and strcat
| Term | Meaning |
|---|---|
strcpy |
copy |
strcat |
append |
dst |
destination array |
src |
source array |