create a typedef of struct and use functions to request data

0

The error tells me:

  

could not convert '(Person) (& p) from' Person * 'to' Person '

struct Persona{
    char nombre[20];
    int edad;
};typedef struct Persona arreglo [5];

Persona cargarArreglo(Persona);
void Imprimir(Persona);

int main()
{
    arreglo p;
    cargarArreglo(p);
    Imprimir(p);
    return 0;
}
    
asked by Juan Manuel Naya 03.07.2018 в 02:29
source

1 answer

0

The problem is that when you create the typedef that way you are telling the compiler that any variable declared as array will be a 5-position array and your functions loadArray and Print they receive a Person data type and you are passing them a 5-position arrangement of Person

If you want to do it that way you should call it the following way

cargarArreglo(*p); or cargarArreglo(&p[i]); Imprimir(*p); or Imprimir(&p[i]);

I recommend this:

typedef struct Persona
{
    char nombre[20];
    int edad;
}Persona;

void cargarArreglo(Persona ** n, int cantidad)
{
    (*n) = (Persona*)malloc(sizeof(Persona) * cantidad);
    memset((*n), 0, sizeof(Persona) * cantidad);

    for(int i = 0; i < cantidad; i++)
    {
        char num = 48 + i;
        strcpy((*n)[i].nombre, "Nombre ");
        strcat((*n)[i].nombre, &num);
        (*n)[i].edad = 20 + i;
    }

void Imprimir(Persona n){
     printf("Nombre = %s, edad = %d", n.nombre, n.edad);
}
int main()
{
    Persona * p;
    int cant = 5;
    cargarArreglo(&p, cant);

    for(int i = 0; i < cant; i++)
        Imprimir(p[i]);

    return 0;
}
    
answered by 05.07.2018 в 23:43