Thread: How to allocate dynamic memory for structure in my code

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Oct 2019
    Posts
    81

    How to allocate dynamic memory for structure in my code

    How to allocate dynamic memory for structure in my code

    I know how to use malloc to allocate dynamic memory

    Code:
    int *ptr = (int *) malloc(4 * sizeof (int));
    if (ptr == NULL) {
        /* Memory could not be allocated
    } else {
        /* Allocation succeeded.  Do something.  */
        free(ptr);  
        ptr = NULL; /* The pointed-to-data  must not be used again,
                       unless re-assigned by using malloc
                       again. */
    }
    How to allocate dynamic memory for the structure in code ?

    Code:
    #include <stdio.h>struct Person
    
     { int N; float height; }p1;
    
    void show_person(struct Person p) {
      printf( "person %d is %f meters tall.\n", p.N, p.height );
    }
    
    void change_height(struct Person *p, float new_height) {
      p->height = new_height;
    }
    
    int main(void) {
        
        p1.N = 1;
        p1.height = 2.0;
        
       show_person(p1);
       change_height(&p1, 1.9)  ;
       show_person(p1);
    
      return 0;
    }
    Last edited by gajya; 11-08-2019 at 07:55 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 04-03-2019, 11:46 AM
  2. structure dynamic memory allocation?
    By mgracecar in forum C Programming
    Replies: 4
    Last Post: 03-15-2012, 11:15 PM
  3. Freeing dynamic allocated memory of structure
    By darekg11 in forum C Programming
    Replies: 14
    Last Post: 01-10-2011, 09:17 AM
  4. Why does this structure allocate memory?
    By sanddune008 in forum C Programming
    Replies: 18
    Last Post: 07-14-2009, 07:31 AM
  5. Allocate a big dynamic memory location
    By vnrabbit in forum C Programming
    Replies: 11
    Last Post: 10-09-2002, 08:02 AM

Tags for this Thread