I'm trying to grasp the concept of arrays of structures and came up with a problem. Hopefully you can help me out.
Okay, so, the problem I'm facing is how to declare and use (i.e. accept & display values) of an array variable within an array of structures?
This sample code may visually help you to understand my problem:
#include<stdio.h>
struct node{
int roll;
char name[10];
int grades[5]; // Accepts 5 grades for each student
};
int main()
{
struct node student[3];
/*Accept and display values for structure members here*/
return 0;
}
I know there's a similar example here.
But I don't understand line 4 in the accepted answer's main()
section, where memory is allocated using malloc()
:
list[ip].inputs[inp]= (char*)malloc(25);
I'm getting confused between the 25 bytes allocated here and the 10 defined in char* inputs[10];
What exactly is happening here? And how do you solve the problem I mentioned above?
There's an extra *
in the example you quote. The malloc
is needed only because of that, in your example inputs
is an array of 10 pointers to char
while here name
is a buffer holding 10 char
s. You don't need any malloc
in your code.
Your structure looks like this in memory (assuming 4-bytes int
s):
Your student
array from main
looks like:
As you see, fields are laid out one after another. Thus, to read the name of the first student you have to write into student[0].name
(using strncpy
to ensure that there's no overflow). To change the third letter of the name of the second student you'll use student[1].name[2]
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments