Returning(Null) when displaying a String variable

Asked

Viewed 367 times

1

The program must receive the name of a person and sex and show the data typed by the user, but when the program shows the name I typed is appearing Null instead of showing the name.

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

main()
{
    setlocale(LC_ALL, "Portuguese");
    char nome, sexo;

    printf("Digite o seu nome: ");
    scanf("%s", &nome);
    printf("Digite o seu sexo M (Masculino) ou F (Feminino): ");
    scanf("%s", &sexo);

    if(sexo=='f' || sexo=='F')
    {
        printf("\nOlá %s o seu sexo é feminino.\n\n", nome);
    }else

    if(sexo=='m' ||sexo=='M')
    {
        printf("\nOlá %s o seu sexo é masculino.\n\n", nome);
    }else

    if(sexo!='f' || sexo!='F' || sexo!='m' || sexo!='M')
    {
        printf("Sexo inválido");
    }

    system("pause");
}

Imagem do Erro

3 answers

2


sexo is the type char, ok, just one character to store it, at least in the form used. But there is an error reading it. To read a data char use the %c in the scanf().

Already in the name is using the correct formatting on scanf(), but is using the wrong type in the variable. A name must be a string, so a string if characters ended by a null. You are only taking the null because you did not declare the variable as a sequence but as a single character.

To declare a sequence we use a pointer or a array. In this case, I think it would be more appropriate array for it to reserve space for the whole variable. So it would be something like char nome[31]. Then you don’t even need to pass the address because a array is already a memory address, already a reference.

In a more organized way the code looks like this:

#include <stdio.h>
#include <locale.h>

int main() {
    setlocale(LC_ALL, "Portuguese");
    char nome[31];
    char sexo;
    printf("Digite o seu nome: ");
    scanf("%30s", nome);
    printf("Digite o seu sexo M (Masculino) ou F (Feminino): ");
    scanf("%c", &sexo);
    if (sexo == 'f' ||  sexo == 'F') printf("\nOlá %s o seu sexo é feminino.", nome);
    else if (sexo == 'm' || sexo == 'M') printf("\nOlá %s o seu sexo é masculino.", nome);
    else printf("Sexo inválido");
}

I put in the Github for future reference.

2

Are you declaring nome as being a char:

char nome, sexo;

There are two alternatives. The first is you declare the variable as a vector, where it will set the maximum length of characters it can store; another is to use a pointer, making it more dynamic.

//opção usando vetor
char nome[256];
//opção usando ponteiro
char *nome;

2

You have to declare char as a vector:

char[numero] nome;

Browser other questions tagged

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