Vector struct and pointers

Asked

Viewed 1,393 times

2

I have to pick up data (name and phone) of some people in a struct, then store them in an array, all this for a function/procedure. At the time of printing comes out some strange characters.

I’m using the DEV C platform++

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

#define MAX 2

typedef struct dadosPessoais    
    { 
        char nome = ' ';
        int telefone = -1;
    }DadosPessoais; 

void inserir(DadosPessoais *vetor);
void listar(DadosPessoais *vetor);

int main()
{

    int escolha=1;
    DadosPessoais vetor[MAX];

// se a escolha for diferente de 3, ele continua... o que inicialmente é verdade
// pois escolha é igual a 1

    while (escolha!=5)
    {

        printf("\n\n ----------------------- ");

        printf("\n 1 - Inserir novo registro ");
        printf("\n 2 - Limpar registros da tabela ");
        printf("\n 3 - Fechar Programa ");
        printf("\n\n Escolha uma opcao: ");
        scanf("%d",&escolha);


// estrutura switch
        switch (escolha)
         {

            case 1:
            {
                system ("cls");
                inserir(vetor);
                break;
            }

            case 2:
            {
                system ("cls");
                listar(vetor);
                break;
            }   

// opção padrão
            default:
            {
                system ("cls");

// se for escolhida a opção 3, ele pula o while utilizando continue para isso 
                if( escolha==3)
                {
                    continue;
                }
// caso o usuário digite um numero acima de 5, ele irá informar que nao existe essa opção
                printf("\n\n Nenhuma opcao foi escolhida ");
                break;
            }
        }   

    }
    if( escolha==3)
    printf("\n\n O Programa foi fechado");

    system("PAUSE"); 

}

void inserir(DadosPessoais *vetor)
{
    int x=3, i, espaco ;

    for(i=0; i<x; i++)
    {
        if (vetor[i].nome == ' ')
        {
            espaco = 1;
            break;
        }
        else
        {
            espaco = 2;
        }       

    }

    if (espaco == 1)
    {
        printf("Digite nome: \n");
        scanf(" %s", &vetor->nome);

        printf("Digite o telefone: \n ");
        scanf(" %d", &vetor->telefone);
    }
    else
    {
        printf("Nao ha espaco vago \n ");
    }
}

void listar(DadosPessoais *vetor)
{
    int x=MAX, i, espaco ;

    for(i=0; i<x; i++)
    {
        if (vetor[i].nome != ' ')
        {
            printf(" %c", &vetor[x].nome);
            printf("\n");
            printf(" %c", &vetor[x].telefone);
            printf("\n");
        }
        else
        {
            printf("Vetor vazio");
        }       
    }

}

1 answer

3


The question could be considered very broad because it has several problems. Stack Overflow works best with well-defined issues in well-focused questions.

I will list some issues of your code that need to be fixed. From there you will be able to improve some things and be able to ask more focused questions when you have a more specific problem.

  1. The guy char stores only one character. To store multiple characters you need to declare as array, something like char nome[40] where you will reserve 40 characters within the struct which is quite inefficient for can be used for educational purposes. Or you can declare as char * nome and can have the size undetermined, occupying only the space for a pointer (then you will have to make the allocation outside).
  2. You don’t initialize the vector. So it’s very easy to pick up a lot of garbage. The fact that you reserve memory for the variable in the declaration does not mean that the memory is wiped.
  3. You are using an integer to store phone. Although a phone number looks like a numeric value it is not. I would use a string for this too. Remembering that if we insist on using a int, cannot use numbers with more than 9 digits or starting with zero (which technically does not exist).
  4. That one if ( escolha==3) within the default is very weird. If you want to do something when the choice is 3, mount a case for that. And put it all there, don’t need to have the other if just below. It’s weirder than while run until the escolha be 5. And another detail, you just need a system ("cls"); throughout your code.
  5. This way of checking if there is space in the vector to put new data is extremely flawed. You would need to initialize the data with NULL and check this.
  6. This variable espaco is completely unnecessary. If you find vacant space in the vector, you process the inclusion there in that if, do not need to create a confusing algorithm.
  7. If you are using an array, you need to use an index in the variable. No scan you probably wanted to do &vetor[i]->nome. And the next probably &vetor[i].telefone (if you’re using a int and not a pointer to int, would have to use the operator . and not the operator ->.
  8. Then in the printf() is using the wrong operator again. You are having the pointer printed when you want to print the content pointed by it, like this: &vetor[x]->nome.
  9. In the printf() would have to use the specifiers %s and %d. The same mistake was made in scanf().
  10. You are using the variable x in the loop but it does not vary, who is varying is the i.
  11. You can only say that the vector is empty if it passes through the whole for and no item is printed, you cannot say this while inside the for.

There are a number of small other details that won’t make as much difference, such as unused variables, or use the MAX and use a literal 3 which does not even match the current value of MAX, inconsistency between pointer use and array, comments that say do something that is not real, etc. that make your code look weird or even wrong.

I haven’t done a very thorough analysis. There may be more mistakes or I may have misunderstood something wrong. You need to improve by parts.

I think I’ve helped a lot more than this just by doing it for you and I’m sure you want to do it on your own.

  • bigown thanks so much for the help, sure I want to finish it on my own, I have to learn neh rsrs...I will try to fix the mistakes, any doubts put Aki again...mto thank you even abços

  • @Zuul headache is to make something look good at all browsers and versions :)

  • 2

    @bigown This is not called a headache, it’s called CSS :D

  • bigown adopted his recommendations, now is much better, but the program can not save the inf of a person, when I ask him to type again and then print he printed only the last record he erases the others.

  • @Murilosilva opens another question by placing the current code and showing where the problem is. If I did, I’ll try to answer it, but someone else might as well. Then it would be nice to do the [tour] of the site to see that you can accept a reply as the most correct that helped you and later when you have more reputation you can vote on all the answers that helped in any way.

Browser other questions tagged

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