I don't know how to pass a pointer to functions and change the values that pointer pointing to,
I did it like this:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct node{
struct node* lchild;
struct node* rchild;
struct node* p;
int noChild;
char* data;
int height;
};
typedef struct node text_t;
text_t * create_text(){
text_t * txt = NULL;
return txt;
}
int length_text(text_t *txt){
if(txt == NULL)return 0;
return txt->noChild+1;
}
char * get_line(text_t * txt, int index){
if(index>txt->noChild+1) return NULL;
text_t * current = txt;
while((current->noChild+1)!=index-1){
if(index-1>current->noChild+1){
current = current->rchild;
}else{
current = current->lchild;
}
}
return current->data;
}
void append_line(text_t *txt, char * new_line){
text_t * temp;
if (txt == NULL){
txt = (text_t *)malloc(sizeof(text_t));
txt->lchild = NULL;
txt->rchild = NULL;
txt->noChild = 0;
txt->p = NULL;
txt->data = new_line;
txt->height = 1;
printf(txt->data);
}else{
text_t * current = txt;
while(current->rchild!=NULL){
current = current->rchild;
}
temp = (text_t *)malloc(sizeof(text_t));
temp->lchild = NULL;
temp->rchild = NULL;
temp->noChild = 0;
temp->data = new_line;
temp->height = 1;
temp->p = current;
}}
int main()
{ int i, tmp; text_t *txt1, *txt2; char *c;
printf("starting \n");
txt1 = create_text();//1
txt2 = create_text();
append_line(txt1, "line one" );//2
...
I want to create an object of such a struct in C and use it to build a balanced tree.
However, after I did append_line(), nothing changes with txt1, it's still NULL. Why?
Thanks
malloc. In particular, instead oftype *ptr = (type *)malloc(sizeof(type));I like to usetype *ptr = malloc(sizeof *ptr);because if the type ofptrchanges, the first line has to be edited in three different places or it will produce errors, while the second only needs to be changed in one. It also helps forreallocs, which generally won't need to change at all.