Thread: Malloc the struct

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    35

    Malloc the struct

    Well I have the struct here, an array of structs actually. I have to malloc it, and then free. How is it done, in codes? Thanks for any help. I'm driven crazy for days but I can't do it.

    Code:
     struct Student
         {
         char id[20], grade;
         int *tests;
         int total;
         };
    
         struct Student Stud[81];

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Put the struct prototype, before main() (global space), and include the header file, stdlib.h.

    Do you want to malloc the int's for tests?
    Code:
    Stud[i].test = malloc(Number of Test int's you want * sizeof(int));
    should do it.

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    You may want to study this link for DYNAMIC MEMORY ALLOCATION .

    Jim

  4. #4
    Registered User
    Join Date
    Apr 2011
    Posts
    35
    Quote Originally Posted by jimblumberg View Post
    You may want to study this link for DYNAMIC MEMORY ALLOCATION .

    Jim
    Thanks a lot! The link helped a lot.

  5. #5
    Registered User
    Join Date
    Apr 2011
    Posts
    35
    Quote Originally Posted by Adak View Post
    Put the struct prototype, before main() (global space), and include the header file, stdlib.h.

    Do you want to malloc the int's for tests?
    Code:
    Stud[i].test = malloc(Number of Test int's you want * sizeof(int));
    should do it.
    Yes, I wanted to malloc them. Thanks for the code!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char** in struct amd malloc()
    By alexopth1512 in forum C Programming
    Replies: 7
    Last Post: 11-03-2010, 03:05 AM
  2. malloc sizeof struct
    By cjohnman in forum C Programming
    Replies: 5
    Last Post: 05-06-2008, 07:49 AM
  3. Help with malloc and a complex struct
    By mc61 in forum C Programming
    Replies: 2
    Last Post: 01-14-2008, 12:12 PM
  4. another malloc of ptr in struct
    By tikelele in forum C Programming
    Replies: 7
    Last Post: 11-20-2007, 03:17 PM
  5. how to use malloc with a struct?
    By allplay in forum C Programming
    Replies: 6
    Last Post: 09-13-2006, 02:49 PM