Reputation: 267
I am using a data structure to implement a spellchecking. I had two struct, node and table, which are defined in the following:
#include <stdlib.h>
typedef struct node *tree_ptr;
typedef struct table * Table;
struct node
{
char* element;
tree_ptr left, right;
};
typedef struct table
{
tree_ptr head;
int tree_h;
}table;
int main() {
Table t = malloc(sizeof(table));
t->head = NULL;
tree_ptr ptr = t->head;
ptr = malloc(sizeof(tree_ptr));
ptr->element = "one";
ptr->left = NULL;
ptr->right = NULL;
printf("%s\n",t->head->element);
return 0;
}
This programme has bug in the last line of print function, since t->head is pointing to NULL.
As I know, when changing a pointer's content value, the variable which the pointer points to is automatically changed.
Since t->head and ptr are both pointers, and ptr points to the t->head, that's, they are pointing to the same object.
Then when I change the ptr's value, why t->head doesn't change in the same way?? What should I do to achieve that t->head changes as ptr changes??
Upvotes: 0
Views: 932
Reputation: 210928
You have to assign ptr
back to t->head
. Apart from this you have to allocate sizeof(struct node)
for one node:
int main() {
Table t = malloc(sizeof(table));
t->head = NULL;
tree_ptr ptr = malloc( sizeof(struct node) );
// ^^^^
ptr->element = "one";
ptr->left = NULL;
ptr->right = NULL;
t->head = ptr; // <-------
printf("%s\n",t->head->element);
return 0;
}
Note ptr = t->head
only assigns the value of t->head
to ptr
. ptr = malloc(....)
allocates dynamic memory and assigns the address of the memory to ptr
and overwrite the value of t->head
which was there before. But the address of the memory is never assigned to t->head
. There is no magical linkage between ptr
and t->head
.
What you tried to do is somthing like this:
tree_ptr *ptr = &(t->head);
*ptr = malloc( sizeof(struct node) );
(*ptr)->element = "one";
(*ptr)->left = NULL;
(*ptr)->right = NULL
In this case ptr
is a pointer to t->head
and *ptr = malloc( sizeof(struct node) )
assigns the address of the allocated memory where ptr
refers to and that is t->head
.
Upvotes: 2