This blog is under construction

Monday 30 April 2012

malloc example in C

Header file:
    stdlib.h

Synopsis:
     void *malloc(size_t sz);

Description:
      It allocates memory of size sz and returns pointer to the allocated memory block.  NULL is returned on error.


malloc function C example:


  #include<stdio.h>
  #include<stdlib.h>
  #include<string.h>
  struct db {
        char name[50];
        int age;
  };

  int main() {
        struct db *data;

        /* dynamic memory allocation */
        data = (struct db*)malloc(sizeof (struct db));

        /* initialization */
        strcpy(data->name, "Micheal Jackson");
        data->age = 50;

        /* printing results to output screen */
        printf("Name: %s\n", data->name);
        printf("Age: %d\n", data->age);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Name: Micheal Jackson
  Age: 50




No comments:

Post a Comment