Hello all,
I would like to ask for some little explanation.
Suppose I have a following code:
Code:
#include<stdio.h>
#include<stdlib.h>
typedef struct {
char* firstName;
char* lastName;
unsigned int age;
char gender;
double hourlySalary;
}Worker;
Worker* initperson(char*, char*, unsigned int, char, double);
int main(void){
Worker *emp;
emp = initperson("David", "Jhonson", 27, 'M', 1578.45);
printf("%s %s age: %d, gender: %c, salary: %.2lf\n",
emp->firstName, emp->lastName, emp->age, emp->gender,
emp->hourlySalary);
return 0;
}
Worker* initperson(char* first, char* last, unsigned int Age, char gend, double salary){
Worker* person = malloc(sizeof(*person));
if(person != NULL){
person->firstName = first;
person->lastName = last;
person->age = Age;
person->gender = gend;
person->hourlySalary = salary;
}
return person;
}
My question is about this line:
Code:
Worker* person = malloc(sizeof(*person));
How this line should be read?
Just've seen some example at old stack-exchange thread and tried to reproduce it with my code.
I mean, normally I would write something like:
Code:
Worker* person;
person = malloc(sizeof(Worker));
// possibly adding casting prior malloc,
// like this: (Worker*)malloc(sizeof(Worker));
But when this have written in a single line, I can't actually get of what actually happens.
It looks like:
Firstly the pointer of Worker type struct is created (still it is not initialized)
Secondly this un-inited pointer is used (or more exactly: a sizeof command evaluates how much memory has been taken by "*person", then this value is used by "malloc" function to create an empty struct in the memory + pass pointer to it.
Anyway, your help will be highly appreciated.
Thanks a lot in advance.