I'm trying to create an array of struct elements, as shown below:
#include <stdio.h>
#include <stdlib.h>
struct termstr{
double coeff;
double exp;
};
int main(){
termstr* lptr = malloc(sizeof(termstr)*5);
return 0;
}
When i compile this, i get errors as follows:
term.c: In function ‘main’:
term.c:11:1: error: unknown type name ‘termstr’
term.c:11:31: error: ‘termstr’ undeclared (first use in this function)
However, when i change my code to the following, it compiles as usual:
#include <stdio.h>
#include <stdlib.h>
typedef struct termstr{
double coeff;
double exp;
}term;
int main(){
term* lptr = malloc(sizeof(term)*5);
return 0;
}
I've added typedef (with type name as term), changed the name of struct to termstr and am allocating memory with term* as the type of pointer.
Is typedef always required for such a situation i.e. for creating arrays of structs? If not, why was the first code giving errors? Is typedef also required to create and use a single instance of a struct?