How to check if the array of a record is empty in C

Asked

Viewed 6,449 times

1

I have this record:

typedef struct{
    char nome[200], telefone[200], email[200];
} Agenda;

Agenda contato;

Agenda vetor[300];

And I want to print out only the records that have data:

int lista_contatos(void){
    printf("========== Contatos ==========\n");

    for(i=0;i<300;i++){

        if(vetor[i].nome == NULL){
          printf("Contatos Listados.");
          main();  
        }else{
            printf(sizeof(vetor[i].nome));
            printf("Nome: %s \n",vetor[i].nome);
            printf("Telefone: %s \n",vetor[i].telefone);
            printf("Email: %s \n",vetor[i].email);
            printf("________________________\n");


        }       
    }   
}

1 answer

2


The question does not give details and does not put important parts to help with more property, including because there may be errors in the part not shown (there are indications that has errors), but in essence in the form presented, which does not seem ideal, has to create a pattern, when creating the array should initialize all elements with an invalid value, it may be for example to put a null (\0) on all three strings in all respects, this indicates that this is not valid data. You have to make sure that if a data is entered it cannot be empty, it has to have at least one space. Then when accessing check the size of the string, if 0 is because the element is empty.

You may be thinking that you don’t need to initialize the 3 like this, and in fact for what you ask in the question you only need one of them, but to keep them in order in all cases it is better to do in the 3, do not use something without initializing.

How did you choose a array inside the structure does not have a pointer and it makes no sense to use the NULL, can but to check whether the first character of the string is null, which is what I indicated to do above, then would:

if (vetor[i].nome[0] == NULL) {

I put in the Github for future reference.

Browser other questions tagged

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