How to pass a struct vector by reference parameter?

1

My question is, what is the error of this passage? It looks like the (*dadosCliente+i) pass is incorrect, does anyone know why?

struct cliente{
    char nome[50];
    char endereco[50];
}

void addCliente(struct cliente *dadosCliente, int *i){
    printf("qual o nome do cliente?");
    scanf(" %s", (*dadosCliente+i).nome);
    printf("qual o endereço do cliente?");
    scanf(" %s", (*dadosCliente+i).endereco);
    *i=*i+1;
}

void main(){
    int i=0,h=0;
    struct cliente clientes[1000];
    while(h!=1){
        printf("Caso queira sair do cadastro digite 1");
        addCliente(clientes, &i);
    }
}
    
asked by anonymous 03.02.2014 / 17:48

3 answers

7

First you need to derrefer i . After that you'll need another couple of parentheses:

(*(dadosCliente+*i)).endereco

or

(dadosCliente+*i)->endereco
    
03.02.2014 / 17:57
1
(scanf(" %s", (*dadosCliente+i).nome);

The changes would need to be these:

(scanf(" %s", (dadosCliente+*i)->nome);

You dereferentiate the i pointer and then sum to the first address of dadosCliente , which dereferences with -> and accesses the name field. Since the name field is a vector, you only need nome , the first address, to save the string, but you could be redundant:

(scanf(" %s", &( (dadosCliente+*i)->(*nome) ));

There are some serious problems with your code ...

  • Looping without end, there will never be a change in the value of h
  • The printf will scan only the first blank space, the rest will remain in the buffer answering subsequent questions
  • Memory Invasions in the Name and Client Vector field; The first one because printf is without limitations, it would need something like: printf(" %50[^\n]s", vetChar) ; The second due to endless looping
  • Here is a study material on printf.

    I hope I have helped. : -)

        
    04.02.2014 / 14:11
    0
    struct cliente{
        char nome[50];
        char endereco[50];
    };//faltava o ponto e virgula
    
    void addCliente(struct cliente *dadosCliente, int *i)//ha duas maneiras de usar o vetor de struct por referencia
    {
        printf("qual o nome do cliente?");
        scanf(" %s", dadosCliente->nome);//a primeira muito mais simples
        printf("qual o endereço do cliente?");
        scanf(" %s", (*(dadosCliente+*i)).endereco);// e aqui no caso pra poder dar certo oq pretendia fazer 
        *i++;
    }
    
    void main(){
        int i=0,h=0;
        struct cliente clientes[1000];
        while(h!=1){
            printf("Caso queira sair do cadastro digite 1");
            addCliente(clientes, &i);
        }
    }
    
        
    02.09.2016 / 19:54