Reputation: 541
I can't seem to understand the difference between the following to pointer notations, can someone please guide me?
typedef struct some_struct struct_name;
struct_name this;
char buf[50];
this = *((some_struct *)(buf));
Now I tried to play around a bit and did the above thing like:
struct some_struct * this;
char buf[50];
this=(struct some_struct *)buf;
As far as I am concerned I think both the implementations should generate the same result, Can someone guide me whether there is a difference between the two and if yes can some one point it out?
Thanks.
Upvotes: 0
Views: 81
Reputation: 79003
Both approaches have their problems.
buf
might not be properly aligned for a variable of the structure type. If so this will produce undefined behavior (UB): in the best case it aborts your program, but it may make much worse things than that.char
is a signed integer type on your platform and you hit a trap representation for char
=> UB as above. (Your second case will encounter the same problem, once you try to access the object at the other end of the pointer.)How to avoid all that:
= { 0 }
should do in all cases.char
as a generic type for bytes but use unsigned char
struct
object to unsigned char
.Upvotes: 0
Reputation: 54631
In your first snippet, this
is not a pointer, it's an instance of some_struct
. The assignment you made did a shallow copy (i.e. memcpy()
) of what's in buf as if it were an instance of some_struct
as well.
In the second snippet, this
is a pointer, and it's just pointed to the address of buf
.
So, basically to sum up, first snippet this
is not a pointer and the struct is copied into it. In the second, it's a pointer and assigned to the same memory as buf
(i.e. not a copy).
Upvotes: 3
Reputation: 391
In the second one, "this" will point to the first memory location of "buf". In the first example, you will either get a compiler error (I don't think you can assign structs in C with =, I could be wrong though), or the contents of buf (up to sizeof(struct_name)) will be copied into this, which resides on the stack.
Upvotes: 0