I am having trouble figuring out how to dynamically allocate memory to a array structure. I need to use an array of my defined structure so that I can iterate over it to print the info. However, I am also asked to dynamically allocate memory to the array.
The problem is that when I use malloc() in the code (you will see it is commented out) it throws the pointer off from the array index. Is there any way to accomplish dynamically allocating memory while pointing to the array indicies to store the data?
DISCLAIMER: I am very new to C, if my coding hurts your eyes, I sincerely apologize in advance. Just looking to understand the program rather than quickly finish it.
PROGRAM INSTRUCTIONS:
Write a C program that uses 'struct' to define a structure containing the following Student:
Information:
- Initial [character]
- Age [integer]
- Id [integer]
- Grade [character]
Your program should print the above information for 5 students.
Hint: Use array of structures and iterate over the array to print the information.
Create a structure with:
- Variable data of type int
- A character pointer called tag. This pointer should point to the address of a string.
Check if memory is available and then dynamically allocate required memory to your structure.
Assign values to your structure variable and print them to console.
Code so far:
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
int main (void)
{
struct student
{
char initial [21];
int age;
float id;
char grade [3];
} list[5];
struct student * tag = list;
//LINE BELOW IS WHAT I WAS TRYING TO DO; BUT THROWS POINTER OFF OF STRUCT ARRAY
//tag = ( struct student * ) malloc ( sizeof ( struct student ));
strcpy(tag->initial, "KJ");
tag->age = 21;
tag->id = 1.0;
strcpy (tag->grade, "A");
tag++;
strcpy(tag->initial, "MJ");
tag->age = 55;
tag->id = 1.1;
strcpy (tag->grade, "B");
tag++;
strcpy(tag->initial, "CJ");
tag->age = 67;
tag->id = 1.2;
strcpy (tag->grade, "C");
tag++;
strcpy(tag->initial, "SJ");
tag->age = 24;
tag->id = 1.3;
strcpy (tag->grade, "D");
tag++;
strcpy(tag->initial, "DJ");
tag->age = 27;
tag->id = 1.4;
strcpy (tag->grade, "F");
tag++;
int n;
for ( n = 0; n < 5; n++ ) {
printf ( "%s is %d, id is %f, grade is %s\n",
list [ n ].initial, list [ n ].age, list [ n ].id, list [ n ].grade);
}
return 0;
}
sizeof(student)mean?), but you pretend you have allocated a whole array of them. That can't work.tagis char pointer in question.But in program it is structure pointer... Give proper info..tagshould be char pointer. Do I declaretagwithin student to make it char pointer? Thank you as well forsizeof(student)advice - your feedback is sincerely appreciate.