This blog is under construction

Monday, 30 April 2012

malloc example in C

Header file:

     void *malloc(size_t sz);

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

malloc function C example:

  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;

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

No comments:

Post a Comment