简体   繁体   中英

using struct array as parameter in c++

I'm having trouble while building this:

#include <stdio.h>
#include <conio.h>
#define N 3

struct cliente
{
    char nocliente[12];
    int edad;
    int precio;        
};

void imprimir(cliente *cliente1[N]);

int main()
{
    struct cliente cliente1[N];
    for(int i=0; i<N; i++)
    {
        printf("\nIngrese el nombre del cliente %d\n", i+1);
        scanf("%s", &cliente1[i].nocliente);
        printf("\nIngrese la edad del cliente %d\n", i+1);
        scanf("%d", &cliente1[i].edad);
        printf("\nIngrese el precio del articulo del cliente %d\n",  i+1);
        scanf("%d\n", &cliente1[i].precio);
    }

    imprimir(&cliente1[N]);

    getch();
    return 0;
}

void imprimir(cliente *cliente1[N])
{
    for(int i=0; i<N; i++)
    { 
        printf("%s", cliente1[i]->nocliente);
        printf("\n%d", cliente1[i]->edad);
        printf("\n%d", cliente1[i]->precio);
    }
}

This is the error the compiler outputs:

cannot convert `cliente*` to `cliente**` for argument `1` to `void imprimir(cliente**)`

I´ve tried declaring (cliente *cliente[]) in the parameters of the prototype and definition but the function but it doesn't work either

Use the following instead :

void imprimir(cliente *cliente1)

for your function declaration.

Make changes to ...

imprimir(&cliente1);//you are passing the whole thing not just #3


void imprimir(cliente *cliente1) //drop the N
  • The correct (and confusing) syntax is

    void imprimir(/* const */ cliente (&cliente1)[N]);

    and then call it

    imprimir(cliente1);
  • A simpler syntax:

     void imprimir(/* const */ cliente *cliente1, std::size_t size);

    with a call

    imprimir(cliente1, N);
  • using class may help as std::vector or std::array

     std::array<cliente, N> cliente1; imprimir(/* const */ std::array<cliente, N>& cliente1);

    And call it

    imprimir(cliente1);

Note: I added const in comment as the array is not modified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM