Why does casting a variable to union type works, but not with struct and array type in c language?
You may have trouble casting if there is a memory size or a memory alignment boundary mismatch between variable and struct.
In general you should be looking for ways to avoid this kind of casting as opposed to opportunities to use it! You will design fewer bugs this way.
For example, in a case like this you could define a union between your variable type and struct. Then you can more safely and sanely reference your data as one or the other.
Since, struct works with multiple objects at a time. Compiler cannot know which data type/ object to cast to it. is it correct?
But, union works with single object at a time. So, there will be no clash regarding which type to choose.
A cast tells the compiler that the storage (raw byte data) associated with an object of one type should instead be interpreted as a different type.
When one of the types is a struct, all storage (each individual member element) is involved. It's not a matter of the compiler knowing which element to use, they're all used.
In order for this to work cleanly and predictably, the two types must have the same size as reported by sizeof().
Yes, as union is concerned, it also behave like as you told. When var cast to union type it will type punning it to as union member. So, compiler assumes all union members are of single entity since it deals with single data type. For struct is concerned, it works with every object.(like we use sizeof to see the difference).
Can you post an example of what doesn't work? I do both and they both work.
Error occurred when compiling was..
error: conversion to non-scalar type requested
int var = 10;
printf("casting variable to struct type...%d", (struct student)var);
Here, you are trying to tell the compiler to make something that is an int (typically 4 bytes) into something that, in this case, is a struct containing, nominally 5 bytes--assuming no alignment filler byte.
That is analogous to trying to park your car in your household refrigerator. It is not going to fit, and so the the compiler produces an error, preventing you from even attempting to do so. To continue, perhaps, the poor analogy... the compiler is your spouse taking away the car keys to prevent you from trying to park the car in the refrigerator....
Real-time analogy is good. Thanks, its understanding.