Comparison of vectors in C

1

I'm currently trying to establish a comparison of two vectors in C.

My code structure is as follows:

int iguais(int *v1, int *v2, int tam) {

    int i, cont = 1;
    for(i=0; i<tam; i++) {
        while(*(v1 + i) == *(v2 + i)) {
            cont++;
        }
    }

    return (cont == tam);

}

Can anyone help me in the debugging process?

    
asked by anonymous 01.11.2016 / 10:01

1 answer

2

You do not need two ties. If both arrays are the same size, just check element-by-element if v1[i] == v2[i] (the pointer syntax is equivalent).

As optimization, instead of counting the amount of equal elements, it is worth checking if there is a different element ( v1[i] != v2[i] ), returning false immediately and avoiding extra iterations:

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

bool iguais(int *v1, int *v2, int tam) {
    int i, cont = 1;
    for(i=0; i < tam; i++) {
        if (v1[i] != v2[i]) {
            return false;
        }
    }

    return true;
}

int main() {
    int v1[] = {1, 2, 3, 4, 5};
    int v2[] = {1, 2, 3, 4, 5};
    int v3[] = {1, 2, 3, 4, 6};

    printf("v1 e v2 sao %s\n", iguais(v1, v2, 5) ? "iguais" : "diferentes");
    printf("v1 e v3 sao %s\n", iguais(v1, v3, 5) ? "iguais" : "diferentes");

    return 0;
}
    
01.11.2016 / 12:04