using malloc for structure

This is a discussion on using malloc for structure within the C Programming forums, part of the General Programming Boards category; Hi all, I'm not new to programming, just new to c Am I correct in assuming that the following two ...

  1. #1
    Pea
    Pea is offline
    Registered User
    Join Date
    Oct 2004
    Posts
    36

    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...

    Code:
    typedef struct tMyStruct{
      int somenumber;
    } tMyStruct;
    
    void main( void ){
      tMyStruct anInstance;
    
      anInstance.somenumber = 5;
    }
    Code:
    typedef struct tMyStruct{
      int somenumber;
    } tMyStruct;
    
    void main( void ){
      tMyStruct *anInstance;
    
      anInstance  = malloc( sizeof(tMyStruct) );
      anInstance.somenumber = 5;
      free(anInstance);
    }
    Cheers,
    Pea

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,853
    > 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
    Location
    Oregon, USA
    Posts
    3,175
    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, 04: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, 06: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-02-2004, 12:36 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21