Posts

Showing posts with the label Struct

C : Typedef Struct Name {...}; VS Typedef Struct{...} Name;

Answer : There are several things going on here. First, as others have said, the compiler's complaint about unknown type may be because you need to define the types before using them. More important though is to understand the syntax of 3 things: (1) struct definition, (2) struct declaration, and (3) typedef. When Defining a struct, the struct can be named, or unnamed (if unnamed, then it must be used immediately (will explain what this means further below)). struct Name { ... }; This defines a type called "struct Name" which then can be used to Declare a struct variable: struct Name myNameStruct; This declares a variable called myNameStruct which is a struct of type struct Name . You can also Define a struct, and declare a struct variable at the same time: struct Name { ... } myNameStruct; As before, this declares a variable called myNameStruct which is a struct of type struct Name ... But it does it at the same time it defines the type str...

C - Freeing Structs

Answer : Simple answer : free(testPerson) is enough . Remember you can use free() only when you have allocated memory using malloc , calloc or realloc . In your case you have only malloced memory for testPerson so freeing that is sufficient. If you have used char * firstname , *last surName then in that case to store name you must have allocated the memory and that's why you had to free each member individually. Here is also a point it should be in the reverse order; that means, the memory allocated for elements is done later so free() it first then free the pointer to object. Freeing each element you can see the demo shown below: typedef struct Person { char * firstname , *last surName; }Person; Person *ptrobj =malloc(sizeof(Person)); // memory allocation for struct ptrobj->firstname = malloc(n); // memory allocation for firstname ptrobj->surName = malloc(m); // memory allocation for surName . . // do whatever you want free(ptrobj->surName); free(ptrobj-...