Segmentation failure - C

Asked

Viewed 50 times

0

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

int validaTipo(char t);

typedef union{
    struct contratoIndividual{
        unsigned int idContrato;
        char cpf[14]; 
        char nome[50]; //Nome completo
        int idade;
        float renda;
    }contI;

    struct contratoColetivo{
        unsigned int idContrato;
        char cnpj[18];
        char razaoSocial[30];
        int quantEmpregMasc;
        int quantEmpregFem;
        int quantDepen;
        float rendaMedia;
    }contC;
}uniao;

int main(void){

    uniao u;
    char tipo;

    printf("Tipo de Contrato: [I/C] ");
    scanf("%c", &tipo);

    printf("%c", tipo);

    if (validaTipo(tipo)){
        printf("Certinho!");
    }
    else{
        printf("Erradnho");
    }

    return 1;
}

int validaTipo(char t){
    char tipos[3] = {'I', 'i', 'C', 'c'};
    for(int i = 0; i < 3; i++){
        if(!strcmp(tipos[i], t)){
            return 1;
        }
    }
    return 0;
}
  • Please Haryel, put the code and not the image.

  • 1

    Be more descriptive in your question and problem. Just playing a 50-line code and saying "Targeting failure" is too vague.

1 answer

2

Haryel, the error occurs because you use strcmp in a char variable, and it actually compares a string, that is, an array of char.

In your case, a simple equality comparison (==) would already solve your problem:

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

int validaTipo(char t);

typedef union{
    struct contratoIndividual{
        unsigned int idContrato;
        char cpf[14]; 
        char nome[50]; //Nome completo
        int idade;
        float renda;
    }contI;

    struct contratoColetivo{
        unsigned int idContrato;
        char cnpj[18];
        char razaoSocial[30];
        int quantEmpregMasc;
        int quantEmpregFem;
        int quantDepen;
        float rendaMedia;
    }contC;
} uniao;

int main(void){

    uniao u;
    char tipo;

    printf("Tipo de Contrato: [I/C] ");
    scanf("%c", &tipo);

    printf("%c", tipo);

    if (validaTipo(tipo)){
        printf("Certinho!");
    }
    else{
        printf("Erradinho");
    }

    return 1;
}

int validaTipo(char t){
    char tipos[4] = {'I', 'i', 'C', 'c'};
    for(int i = 0; i < 4; i++){
        if (tipos[i] == t) {
            return 1;
        }
    }
    return 0;
}

Its type array statement was also incorrect, having only 3 positions, so 'c' was considered an error.


Here’s an example of using strcmp:

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

int main(void){

    char nome[7] = "Daniel";
    char comp[7] = "Daniel";
    char erro[7] = "daniel";

    printf("\nResultado da strcmp 01: %d", strcmp(nome, comp));
    printf("\nResultado da strcmp 02: %d", strcmp(nome, erro));

    return 1;
}

Browser other questions tagged

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