Comparison of vectors in C

Asked

Viewed 1,521 times

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 someone help me in the debugging process?

  • Now it worked.

  • Now I’ve seen that always returns true.

1 answer

3


You don’t need two loops. 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 fake 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.