Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have two structure

C
struct list
{
	char *name;
	int ID;
	int marks[5];
}

struct Employee
{  
    char *school_name;
    unsigned long int ID;
    struct list * student_list;  
	//here i want to use pointer only, because i don't know student si
};

struct Employee high_list;

Here i want to 20 students name, ID, marks for one school; like
C
high_list.student_list[0].ID =20;
high_list.student_list[2].ID =20;
high_list.student_list[3].ID =30;
high_list.student_list[4].ID =30;
high_list.student_list[0].mark[0] =20;
high_list.student_list[2].mark[1] =20;
high_list.student_list[3].mark[0] =30;
high_list.student_list[4].mark[4] =30;

How can i do memory allocation for 20 student list;
.student_list=(struct list *)malloc(sizeof(struct list)); //this is for one list
if i do(struct list) *20 ???

want to allocate for 20 students

What I have tried:

dynamic memory alocation
malloc(sizeof(struct list)*20)
Posted
Updated 19-Nov-22 8:53am
v2

Indeed you may either use
C
high_list.student_list = (struct list *) malloc( sizeof(struct list ) * 20);
or
C
high_list.student_list = (struct list *) calloc( 20, sizeof(struct list) );

By the way, remember to:
  • Check the return value of the malloc (or calloc) call, since memory allocation might fail.
  • Free the allocated memory when you don't need it any longer.
 
Share this answer
 
v3
Comments
merano99 19-Nov-22 9:05am    
+5
Palini's solution works as proposed.
C
struct Employee high_list;

high_list.student_list = (struct list *) calloc(20, sizeof(struct list));
if (high_list.student_list == NULL) return -1;

Of course, the includes <stdio.h> and <stdlib.h> must be used and there should be a semicolon at the end of a structure definition.

Attention: For the strings name and school_name you also need memory as soon as you use them!
 
Share this answer
 
v2
I use a macro for this :
C++
#define AllocateMemory(count,type)	(type*)calloc(count,sizeof(type))

   // and how it's used

   high_list.student_list = AllocateMemory( 20, struct list );
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900