gpt4 book ai didi

我可以像这样更改结构对象中的值吗?

转载 作者:行者123 更新时间:2023-11-30 14:27:36 24 4
gpt4 key购买 nike

我不知道如何将指针传递给函数并更改指针指向的值,

我是这样做的:

#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
...

我想在 C 中创建一个这样的结构体的对象,并用它来构建一个平衡树。

但是,在我执行append_line()之后,txt1没有任何变化,它仍然是NULL。为什么?

谢谢

最佳答案

这是因为c是按值传递

 void append_line(text_t *txt, char * new_line){ 
// ....

txt = (text_t *)malloc(sizeof(text_t));

// .....
}

int main() {
// ...
append_line(txt1, "line one" );
// ...
}
main 中的

txt1 不受 txt 的 appen_line 中的 malloc 语句影响。如果您想影响 main 中的 txt1,请将函数 text_t 参数更改为指向指针的指针。

void append_line(text_t **txt, char * new_line);

现在从 main 传递 txt1 的地址 -

append_line(&txt1, "line one" );

关于我可以像这样更改结构对象中的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7700920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com