Reputation: 11
I was working on a prob and as a part of it came across problem of the follwing type...
For the foll code
#include<stdio.h>
#include<stdlib.h>
typedef struct sample
{
int a;
char b;
}sample;
int main()
{
char *buf;
buf = (char *)malloc(sizeof(char)*sizeof(sample));
buf = ((sample *) buf);
buf->a = 10;
buf->b = 'm';
printf("%d\n",(buf)->a);
printf("%c\n",(buf)->b);
return 0;
}
Compile time error was:
example.c:16: error: request for member a' in something not a structure or union
example.c:17: error: request for member
b' in something not a structure or union
Is this because I cannot typecast a lower data type to higher type..??
I tried using Calloc in place of malloc so that a contiguos block can be allocated but to no avail..
Help me find the logical flaw in this conversion...
Thanks in advance
Upvotes: 1
Views: 2244
Reputation: 16701
buf
's type is still char *
. Casting does not change the type of the receiving variable. The casts you are doing here is essentially pointless - the value of a pointer is not influenced by what it points to. Memory is memory.
To fix this, change the type of buf
to sample *
.
To fix it even further, remove the cast from malloc
and the "recasting" of buf
after it.
Upvotes: 0
Reputation: 7468
The line buf = ((sample *) buf);
doesn't do anything. The variable buf
still is of type char*
.
sample* sample = (sample*)malloc(sizeof(sample));
sample->a = 10;
sample->b = 'm';
printf("%d\n",(sample)->a);
printf("%c\n",(sample)->b);
Is more like what you want.
Upvotes: 2
Reputation: 68962
Yopu should change
char *buf;
buf = (char *)malloc(sizeof(char)*sizeof(sample));
to
sample *buf;
buf = (sample *)malloc(sizeof(sample));
because declaring buf as char * prevents the compiler from understand your intention (to point to a sample structure).
Upvotes: 4
Reputation: 17127
the type of buf does not change with the cast, you need to add an extra variable:
char* buf;
sample* s;
buf = malloc(sizeof(sample));
sample = (sample*)buf;
the sizeof(char)
is completely superfluous by the way, it is 1 by definition.
Upvotes: 0