I'm learning about structs and memory allocation.
One of the things i found out by studying was that there is not a way to see if a block of memory was allocated correctly.
I think it's working properly, but i was getting ready to read about linked lists and got all confused again.
I ask this, because on linked lists, i have seen:
typedef LIST* Lint;
int main(){
Lint *lint;
}
and by defining the type of class like this on my code:
typedef CLASS* t;
int main(){
t class; // WITHOUT THE * BEFORE class
}
it worked! I thought it would be ok, to give the definition like this. To me makes sense, the class is now a pointer to a type (type ie. CLASS);
So, am i on the right track or this working was pure luck?
The code structure sucks, but i'm still learning :)
typedef struct student {
char name[50];
int grade;
} TURMA;
typedef CLASS* t;
void showS(struct student i){
printf("Name of Student: %s \n Grade of Student: %d\n", i.name, i.grade);
}
void insert(struct student *i,int k){
char n[100]; int q=0;
printf("Define name of student %d\n", k+1); scanf("%s", n);
printf("Define the grade of %s\n", n); scanf("%d", &q);
strcpy(i->name,n);
i->grade = q;
}
int main()
{
t class;
int total,plus,i;
printf("Define number of total students: \n"); scanf("%d", &total);
class = (struct student*) malloc(total*(sizeof(CLASS)));
for(i=0; i<total; i++){
insert(&class[i], i);
}
printf("\n\nThis is the complete class: \n");
for(i=0; i<total; i++){
showS(class[i]);
}
printf("(Total size after malloc: %lu) Add more students (Int)\n",sizeof(*turma)); scanf("%d", &plus);
class = realloc(class, plus*sizeof(CLASS));
free(class);
printf("(Total size after malloc: %lu)", sizeof(*class));
return 0;
}
class = malloc(total*(sizeof(CLASS)));
is all that is needed. (presumingCLASS
is correct.). Also parenthesis are only needed when usingsizeof
with a datatype
(e.g.sizeof (int)
), not when taking the size of a variable.sizeof(*class)
can be simplysizeof *class
Lint *lint
instead ofLint lint
? Notice myt class
, should it bet *class
? This last option would make the pointer class a pointer to a struct student right?typedef CLASS* t
makest
an alias forclass*
(i.e. a pointer toclass
)typedef Lint
allows creating a pointer of typeLint
to point to the next node in the linked list. (e.g.Lint *lint;
). However, you will never get to that point unless you define whatCLASS
is. You are trying to create atypedef
fort
from an uknown type. We need more of your code. See: How to create a Minimal, Complete, and Verifiable example."