Dynamic allocation with struct

Asked

Viewed 936 times

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

This is giving the compiler these errors. I think I have declared wrong something or I have not yet understood right to dynamic allocation someone can 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;
}

1 answer

3


In fact the allocation of structit doesn’t do so. One should take the size of it, I don’t know why it is getting 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 members without the variable they are. I also deleted the variable x, unused.

I haven’t changed other things that would be better because you’re 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • bigown Show me some website or book so I can study , I want to learn a lot about it and master this subject, so I can help the community and my classmates.

  • Take a look here: http://answall.com/tags/c/info. Now you can vote on everything on the site, not just the things you asked. You can learn from here: http://answall.com/questions/tagged/c?sort=votes&pageSize=50

Browser other questions tagged

You are not signed in. Login or sign up in order to post.