String Copy in C

Level 4161 keystrokes

Implements a string copy function using pointers.

C code

// dest receives the copy; const char *src promises not to modify the source
1void strCopy(char *dest, const char *src) {
// Loop until *src is the null terminator '\0' (which is false)
2 while (*src) {
// Copy the current character
3 *dest = *src;
// Move both pointers to the next character
4 dest++;
5 src++;
6 }
// The loop stops before copying '\0', so add it to end the string
7 *dest = '\0';
8}
// Destination buffer; it must be large enough ("Hello" needs 6 bytes)
9char str[20];
// Copy the string literal into str
10strCopy(str, "Hello");
// Prints Hello
11printf("%s", str);

Output

Hello
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 7
  • *× 6
  • "× 4
  • (× 4
  • )× 4
  • +× 4
  • ,× 3
  • '× 2
  • {× 2
  • }× 2

More C examples at level 4

← C typing practice