Thread: using malloc for structure

  1. #1
    Registered User
    Join Date
    Oct 2004

    using malloc for structure

    Hi all,

    I'm not new to programming, just new to c

    Am I correct in assuming that the following two code snippets do exactly the same thing? If not, please tell! If so, why would you use one over the other...

    typedef struct tMyStruct{
      int somenumber;
    } tMyStruct;
    void main( void ){
      tMyStruct anInstance;
      anInstance.somenumber = 5;
    typedef struct tMyStruct{
      int somenumber;
    } tMyStruct;
    void main( void ){
      tMyStruct *anInstance;
      anInstance  = malloc( sizeof(tMyStruct) );
      anInstance.somenumber = 5;

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > void main( void ){
    int main

    > anInstance.somenumber = 5;
    Use the arrow operator when you have a pointer to a structure
    anInstance->somenumber = 5;

    Other than that, looking good.

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Oregon, USA
    malloc()'ing space for a struct is especially useful any time that you don't know how many struct instances you're going to need, just like the reason for using malloc() with any other data type. It's really useful for things like linked lists.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  4. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM
  5. malloc always setting length of 8?
    By Zarkhalar in forum C++ Programming
    Replies: 7
    Last Post: 08-01-2004, 11:36 PM