Lately, while working in C, I was developing a generic function. Here is the layout of structure:
typedef struct student_{
char name[32];
int roll_no;
unsigned int height;
} student_t;
and below is my function. What all the function does is, it compares the given instance of a structure with one of the keys ( and hence generic). Here the key being roll_no
static int
check_student_by_roll_number(void *data,void *key){
student_t * student = (student_t*) data;
unsigned int roll_no = *(unsigned int*)(key); // Getting segmentation fault here
if(student->roll_no == roll_no)return 0;
return -1;
}
But the same fault code, when I write as
unsigned int roll_no = *(unsigned int*)(&key);
I am calling the function as
check_student_by_roll_number(john,(void*)40); // john is a pointer to valid structure
The segmentation fault is gone and code works fine.So what is difference between
*(unsigned int*)(key)
and *(unsigned int*)(&key)