strcpy and strncpy in C: solved safe-copy exercise

strcpy and strncpy in C: solved safe-copy exercise

This exercise is scheduled for daily publication and follows the same didactic structure used across the site: clear statement, compilable code, and expected output.

Problem statement

Implement a practical example of the topic and validate the output in the console.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <stdio.h>
#include <string.h>

int main(void) {
    char origen[] = "programacion en c";
    char destino1[32];
    char destino2[8];

    strcpy(destino1, origen);
    strncpy(destino2, origen, sizeof(destino2) - 1);
    destino2[sizeof(destino2) - 1] = '\0';

    printf("destino1: %s\n", destino1);
    printf("destino2: %s\n", destino2);
    return 0;
}

Expected output

1
2
destino1: programacion en c
destino2: program

Common mistakes

  • Not validating input and standard-library return values.
  • Ignoring edge cases (buffers, limits, null pointers).
  • Skipping basic compile/run verification.

Practical use

strcpy and strncpy are the foundation of string copying in C, used in name assignment, file paths, and messages.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful for C exams and technical interviews?

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

Where can I keep practicing with more solved C exercises?

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.