Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created December 30, 2020 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/49166dcaee4532216c40be8e0ebffbca to your computer and use it in GitHub Desktop.
Save parzibyte/49166dcaee4532216c40be8e0ebffbca to your computer and use it in GitHub Desktop.
// https://parzibyte.me/blog
#include <stdio.h>
#include <string.h> // strncpy
#define MAXIMA_LONGITUD_CADENA 50
int main(void)
{
char nombre[MAXIMA_LONGITUD_CADENA] = "Luis";
char otroNombre[MAXIMA_LONGITUD_CADENA] = "Maria";
char temporal[MAXIMA_LONGITUD_CADENA];
printf("Nombre: %s. Otro nombre: %s\n", nombre, otroNombre);
/*
Ahora vamos a intercambiar los nombres. En un escenario ideal haríamos:
temporal = nombre;
nombre = otroNombre;
otroNombre = temporal;
Pero no es posible
*/
// Copia a temporal, lo que hay en nombre, pero solo copia
// MAXIMA_LONGITUD_CADENA de bytes
strncpy(temporal, nombre, MAXIMA_LONGITUD_CADENA);
// Copia a nombre, lo que hay en otroNombre
strncpy(nombre, otroNombre, MAXIMA_LONGITUD_CADENA);
// Y copia a otroNombre, lo que hay en temporal
strncpy(otroNombre, temporal, MAXIMA_LONGITUD_CADENA);
printf("Nombre: %s. Otro nombre: %s", nombre, otroNombre);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment