The malloc() and struct storage - dynamic memory allocation



Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Allocate memory storage for struct

To show: The malloc() C function and struct data storage - the dynamic memory allocation



/* malloc() and struct */

#include <stdio.h>

#include <stdlib.h>


struct record{

char name[15];

int age;

int id_num;



int main(void)


struct record *ptr;

printf("\n--malloc() & struct--\n");

ptr = (struct record *)malloc((sizeof(struct record)));

printf("The size of the struct record: %d bytes\n", sizeof(struct record));



printf("The size of the ptr->name: %d bytes\n", sizeof(ptr->name));

printf("The size of the ptr->age: %d bytes\n", sizeof(ptr->age));

printf("The size of the ptr->id_num: %d bytes\n", sizeof(ptr->id_num));

printf("\nStudent Name: ");


/* gets(ptr->name); */

gets_s(ptr->name, sizeof(ptr->name));

printf("Student Age: ");


/* scanf("%d", &ptr->age); */

scanf_s("%d", &ptr->age, sizeof(ptr->age));

printf("Student Id: ");


/* scanf("%d", &ptr->id_num); */

scanf_s("%d", &ptr->id_num, sizeof(ptr->id_num));

printf("\nStudent Name: %s", ptr->name);

printf("\nStudent Age: %d", ptr->age);

printf("\nStudent Id Number: %d\n", ptr->id_num);




printf("\nMemory allocation fails!!!\n");

return 0;



Output example:


--malloc() & struct--

The size of the struct record: 24 bytes

The size of the ptr->name: 15 bytes

The size of the ptr->age: 4 bytes

The size of the ptr->id_num: 4 bytes

Student Name: Jennifer

Student Age: 24

Student Id: 8734

Student Name: Jennifer

Student Age: 24

Student Id Number: 8734

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index