"Tom St Denis" <to********@gmail.comwrites:
Neha wrote:
>typedef struct AAA
{
unsigned char str;
}Abbb;
typedef struct BBB
{
Abbb ab;
}Bbbb;
int main()
{
void *a;
a= (Bbbb *) malloc(sizeof(Bbbb));
a->ab.str='c';
printf("%c",a->ab.str);
What type is "a"?
Casting changes the interpretation in an expression, not the data type.
[snip]
That's an odd way of putting it.
A cast is an expression that specifies a conversion. The operand of
the cast is of some type (void* in this case); the result is of the
type specified in the cast (Bbbb* in this case). In both cases, we're
talking about types of expressions, not of objects.
Assigning a value to an object *never* changes the type of the object;
it can only change its value. The fact that that value happens to be
the result of a conversion to some type doesn't change that.
So let's look at what happens in the assignment statement
a= (Bbbb *) malloc(sizeof(Bbbb));
malloc() returns a result of type void*. You convert that result from
void* to Bbbb*. You then assign the result of the conversion (which
is of type Bbbb*) to an object of type void*. This is allowed because
there's an implicit conversion from void* to any pointer-to-object
type, and vice versa. So the result of malloc() is converted
explicitly from void* to Bbbb*, and then implicitly back to void*.
Here's how I'd write it:
#include <stdio.h>
#include <stdlib.h>
struct AAA {
unsigned char str;
};
struct BBB {
struct AAA ab;
};
int main(void)
{
struct BBB *a;
a = malloc(sizeof *a);
if (a == NULL) {
fprintf(stderr, "malloc failed\n");
exit(EXIT_FAILURE);
}
a->ab.str = 'c';
printf("%c\n", a->ab.str);
return 0;
}
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.