Dynamic allocation with struct

0
/*  [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
*/

You are giving these compiler errors. I think I said something wrong or I still did not understand the right allocation dynamics can anybody 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;
}
    
asked by anonymous 04.05.2016 / 17:41

1 answer

2

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

There was also an error at the time of printing that tried to access the members without the variable they are. I also deleted the variable x , not used.

I have not changed other things that would be better because you are 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);
    return 0;
}

See running on ideone .

    
04.05.2016 / 17:52