another malloc of ptr in struct
Hi, revisiting the old malloc of pointer in a struct.
This time the I am using a string and I am wandering around again.
Here's what I have
Code:
#include "stdio.h"
#include "math.h"
#include "string.h"
#include "stdio.h"
#define MaxNameLen 512
#define MaxNum 10
struct Students
{
char **names[MaxNameLen + 1];
char grades;
};
typedef struct Students Students;
int main(int argc, char** argv)
{
int i,j;
int numStudents;
Students stu;
do{
printf( "Enter the number of students (1-10): ");
scanf( " %d", &numStudents);
}while(numStudents <= MaxNum && numStudents > 0);
printf( "Enter the %d names and grades: ", numStudents);
stu.names = malloc(numStudents * sizeof(names));
for (i = 0; i < numStudents; i++)
{
stu.names[i] = malloc(stu.grades * sizeof(stu.names[i]));
printf( "Name %d: ", i + 1);
fgets(stu.names[i],MaxNameLen + 1,stdin);
for (j = 0; j < numStudents; j++)
{
printf( "Grade %d", j + 1);
scanf( " %s", stu.grades);
(stu.names[i][j] = stu.grades);
}
}
for (i = 0; i < numStudents; i++)
{
for (j = 0; j < numStudents; j++)
{
printf("%s ",stu.names[i]);
printf( "%s", stu.names[i][j]);
}
printf("\n");
}
for (i = 0; i < numStudents; i++)
{
free(stu.names[i]);
}
free(names);
return 0;
}
this is the trouble spot:
Code:
stu.names = malloc(numStudents * sizeof(names));
I assume allocating char type make a difference.
Thanks for any insight on this.