I init a Struct member like this below:
struct MyStruct
{
int member_a;
};
int
main(){
MyStruct s;//method 1
MyStruct *
ps;//method 2
return
0;
}
What's
the difference between method 1 and 2 ??Why do someone use method 1 and some others use
method2?
Answer
I generally use method_2. In data structures
like binary trees, if I have a pointer to a struct_node, say temp_pointer, and now I
need to change this to its left_child, I can simply make the pointer point to the
left_child. Now, if I need to change some value in the left_child, I can simply change
that value in the node to which temp_pointer points. This won't be possible with
method_1. As there, we would have a separate copy of the left_child instead of a pointer
to the left_child (a separate copy will have same values, but different address).
method_1 will not change the value in the original node (i.e. the left_child), but only
in the copy.
Also, suppose we have a
mystruct_pointer and another temp_pointer. We can compare both (mystruct_pointer ==
temp_pointer), and check whether they point to the same node or not. This won't be
possible with method_1.
Remember, this method_2
only declares a pointer to mystruct type. To actually create mystruct type, you will
have to allocate memory using malloc or calloc.
No comments:
Post a Comment