Dynamic allocation with struct

/*  [Error] expected primary-expression before'*' token
    [Error] 'dia' was not declared in this scope
    [Error] 'mes' was not declared in this scope
    [Error] 'ano' was not declared in this scope
*/

Is giving the compiler these errors. I think I have declared something wrong or have not yet understood right to dynamic allocation can someone help me

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

int main ()
{   
 struct calendario
 {
 int dia;
 int mes;
 int ano;
 };
 struct calendario x,*ptr;
ptr= malloc(calendario * sizeof(int));
  ptr->dia = 5;
  ptr->mes=10;
  ptr->ano=1990;
   printf("%i",dia);
   printf("%i", mes);
   printf("%i",ano);
system("pause>null");
return 0;
}
Author: Maniero, 2016-05-04

1 answers

In fact the allocation of struct is not done like this. You should take the size of it, I don't know why you're taking the size of a int if you want to allocate the structure. And multiplication only makes sense if it is to allocate multiple instances of the structure.

There was also an error when printing that tried to access members without the variable they are. I also eliminated the variable x, not used.

I did not change other things that would be better because it is still learning:

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

int main() {   
    struct calendario {
        int dia;
        int mes;
        int ano;
    };
    struct calendario *ptr = malloc(sizeof(struct calendario));
    ptr->dia = 5;
    ptr->mes = 10;
    ptr->ano = 1990;
    printf("%i/%i/%i", ptr->dia, ptr->mes, ptr->ano);
}

See working on ideone. E no repl.it. also I put on GitHub for future reference .

 3
Author: Maniero, 2020-10-23 18:27:21