Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

659
Vistas
Why I am getting wrong output for source string when I am implementing strcat()?

Here I tried implementing strcat function in C. Problem is that when I am printing the source string it is showing me "hyam" not "shyam"

#include <stdio.h>
#include <string.h>

char *fun(char *target, const char *source) {
    printf("%s\n", source);
    int x = strlen(target);
    while (*source != '\0') {
        *(target + x++) = *source++;
    }
    *(target + x) = '\0';
    return target;
}

int main() {
    char target[] = "ram";
    char source[] = "shyam";
    fun(target, source);
    printf("%s\n", target);
    printf("%s", source);
    return 0;
}

Here in last line of output hyam is shown but it should be shyam.

shyam
ramshyam
hyam
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Your target array is too small - it needs at least nine elements (the length of both strings plus a terminating zero).

Writing outside target has undefined behaviour, but in practice, it looks like your arrays happen to be laid out end to end, like this:

 |r|a|m|\0|s|h|y|a|m|\0|
 ^        ^
 |        | 
target   source

and then you concatenate, going past the end of target into source:

 |r|a|m|s|h|y|a|m|\0|\0|
 ^       ^
 |       | 
target  source

which makes it look like an 's' has disappeared.

(Note that this is undefined, so anything can happen. You can't rely on this behaviour, unless the documentation for your compiler says that it's fine and should do this. Which it most likely won't.)

over 4 years ago · Santiago Trujillo Denunciar

0

The problem is the array target defined with char target[] = "ram"; is too short to accommodate appending the contents of the source string. You must make target larger, at least 9 bytes, 8 for the characters and one more for the null terminator:

char target[9] = "ram";
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda