Giving Segmentation Failure Error (recorded core image)

0

Exercise = Do a procedure that receives, by parameter, 2 vectors of 10 elements integers and that also computes and returns, by parameter, the vector intersection of the two first.

My code:

#include <stdio.h>
#include <stdlib.h>
#define TAM 10

void interseccao(int vetor1[], int vetor2[], int vetor_interseccao[], int *x) {

int i, j;
int aux[50], x_aux = -1;


for (i = 0; i < TAM; i++) {
    for (j = 0; j < TAM; j++) {
        if (vetor1[i] == vetor2[j]) {
            x_aux++;
            aux[x_aux] = vetor1[i];
        }
    }
}


if (x_aux != -1) {
    x_aux++;
    for (i = x_aux-1; i > - 1; i--) {
        for (j = 0; i < x_aux; j++) {
            if (i != j) {
                if (aux[i] == aux[j]) {
                    aux[i] = 0;
                }
            }
        }
    }

    for (i = 0; i < x_aux; i++) {
        if (aux[i] != 0) {
            *x = *x +1;
            vetor_interseccao[*x] = aux[i];
        }
    }

}

}
int main () {

    int vetor1[TAM], vetor2[TAM], vetor_interseccao[TAM];
    int cont, x = -1;

    for (cont = 0; cont < TAM; cont++) {
        printf("Informe o valor do vetor1[%d]: ",cont+1);
        scanf("%d",&vetor1[cont]);
    }

    system("clear");

    for (cont = 0; cont < TAM; cont++) {
        printf("Informe o valor do vetor2[%d]: ",cont+1);
        scanf("%d",&vetor2[cont]);
    }

    system("clear");

    printf("---------------------------------------------------\n");
    printf("Valores do vetor1:\n\n");
    for (cont = 0; cont < TAM; cont++) {
        printf("vetor1[%d] = %d\n",cont+1,vetor1[cont]);
    }

    printf("\n---------------------------------------------------\n");
    printf("Valores do vetor2:\n\n");
    for (cont = 0; cont < TAM; cont++) {
        printf("vetor2[%d] = %d\n",cont+1,vetor2[cont]);
    }

    interseccao(vetor1,vetor2,vetor_interseccao,&x);
    printf("\n---------------------------------------------------\n");
    printf("Valores do vetor_interseccao:\n\n");
    if (x != -1) {
        x++;
        for (cont = 0; cont < x; cont++) {
            printf("vetor_interseccao[%d] = %d\n",cont+1,vetor_interseccao[cont]);
        }
    } else {
        printf("Não há valores de intersecção entre o vetor1 e o vetor2.\n");
    }

    printf("\n");

    return 0;
}
    
asked by anonymous 05.06.2017 / 15:53

1 answer

0

Good afternoon,

"Debugging" your code noticed a silly error in a loop inside the intersection procedure where you changed the comparison variable from "J" to "I" by mistake. Here is the corrected code snippet:

for (i = x_aux-1; i > - 1; i--) {
    for (j = 0; j < x_aux; j++) { //A condição estava i < x_aux
        if (i != j) {
            if (aux[i] == aux[j]) {
                aux[i] = 0;
            }
        }
    }
}

I hope I have solved your problem.

Sincerely, Arthur Passos.

    
05.06.2017 / 20:24