Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created July 12, 2019 00:05
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/ef780a5d6d97cc3ebf3cb3f2b8cfee71 to your computer and use it in GitHub Desktop.
Save parzibyte/ef780a5d6d97cc3ebf3cb3f2b8cfee71 to your computer and use it in GitHub Desktop.
#include <stdio.h>
/*
Comparación de arreglos en C
encerrando comportamiento en función
By parzibyte
Visita mi blog: https://parzibyte.me/blog
*/
// Prototipo de función. Necesitamos la longitud porque no se puede obtener
// dentro de la función
int arreglosSonIguales(int longitudArreglo1, int longitudArreglo2, int arr1[],
int arr2[]);
int main(void) {
int arreglo[] = {1, 2, 3};
int otroArreglo[] = {1, 2, 4}; // Ojo: el último número cambia
// Obtener su longitud para llamar a función
int longitudDeArreglo = sizeof(arreglo) / sizeof(arreglo[0]),
longitudDeOtroArreglo = sizeof(otroArreglo) / sizeof(otroArreglo[0]);
int sonIguales = arreglosSonIguales(longitudDeArreglo, longitudDeOtroArreglo,
arreglo, otroArreglo);
if (sonIguales) {
printf("Los arreglos son iguales");
} else {
printf("Los arreglos NO son iguales");
}
}
// Función que indica si dos arreglos son iguales
int arreglosSonIguales(int longitudArreglo1, int longitudArreglo2, int arr1[],
int arr2[]) {
if (longitudArreglo1 != longitudArreglo2) {
return 0;
}
for (int i = 0; i < longitudArreglo1; i++) {
// Obtener elementos de ambos arreglos en misma posición o índice
int valorDelArreglo = arr1[i], valorDelOtroArreglo = arr2[i];
// Comparar ;)
if (valorDelArreglo != valorDelOtroArreglo) {
return 0; // Terminar ejecución porque no son iguales
}
}
// Si terminamos el ciclo y ningún valor fue diferente, entonces
// ambos arreglos son iguales
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment