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
It’s because c is pass by value.
txt1in main isn’t affected with the malloc statement in the appen_line totxt. If you want to affect thetxt1in main then change the function text_t parameter to pointer to a pointer.Now pass the address of
txt1from main –