gpt4 book ai didi

c - 如何从函数返回链表?

转载 作者:行者123 更新时间:2023-11-30 19:51:25 24 4
gpt4 key购买 nike

首先,抱歉我的英语不好,希望你理解我。我是编程新手,在老师要求我们做的一个小项目中需要帮助。 (家庭作业。)在本作业中,我创建了一个链接列表:

struct No {
char Nome[30];
char Endereco[30];
int Numero;
int aux;
struct No *prox;
};
typedef struct No no;

然后,我添加了函数来填充数组。问题在于我的函数之一没有以任何方式更改数组,就像我根本没有调用该函数一样。以下是重要部分:

int main(void)
{
no *lista = (no *) malloc(sizeof(no)); //This is the linked list I'm talking about.

Contagem=0;

int iOpcao;
while(iOpcao) {
iOpcao=Escolha();
if(selecionarOpcao(lista,iOpcao) == 0)
return 0;
}

return 0;
}

int selecionarOpcao(no *entrada, int op)
{
no *tmp;
switch(op){
case 0:
return 0;

case 1:
ListarContatos(entrada);
break;

case 2:
AdicionarContato(entrada);
break;

case 3:
RemoverContato(entrada);
break;

case 4:
EditarContato(entrada);
break;

case 5:
entrada = OrganizarLista(entrada); //This is the function not working correctly, the other ones are working perfectly fine.
break;

default:
printf("Comando invalido\n\n");
}
return 1;
}

最后是函数本身:

no* OrganizarLista(no* entrada) {
no* ordenada = (no *) malloc(sizeof(no));
no* temp = entrada;
no* maiorNo = NULL;

while(1 == 1) {
while(temp != NULL) {
temp = temp->prox;
if(temp != NULL) {
if(JaExistente(ordenada, temp->Numero) == 1)
continue;

if(temp->prox != NULL && maiorNo == NULL) {
if(JaExistente(ordenada, temp->prox->Numero) == 1) {
maiorNo = temp;
continue;
}

//printf("%s contra %s", temp->Nome, temp->prox->Nome);
if(maiorNo == NULL)
maiorNo = CompararNos(temp, temp->prox);

//printf("%s ganhou.\n", maiorNo->Nome);
}
else if(maiorNo != NULL) {
//printf("%s contra %s", maiorNo, temp->Nome);
maiorNo = CompararNos(maiorNo, temp);
//printf("%s ganhou.\n", maiorNo->Nome);
}
}
}

if(maiorNo != NULL) {
//printf("Maiorno->nome = %s", maiorNo->Nome);
AdicionarLista(ordenada, maiorNo->Nome, maiorNo->Endereco, maiorNo->Numero, 1);
temp = entrada;
maiorNo = NULL;
}
else {
temp = entrada;
while(temp != NULL) {
if(JaExistente(ordenada, temp->Numero) == 0)
AdicionarLista(ordenada, temp->Nome, temp->Endereco, temp->Numero, 1);
temp = temp->prox;
}
break;
}
}
free(temp);

return ordenada;
}

我花了一整天的时间试图弄清楚它,但它仍然不起作用。当我检查函数内的值时,它们都是正确的,但是当返回值时,程序似乎忽略它们。感谢您的帮助,再次抱歉我的英语,谢谢大家!

最佳答案

您正在尝试为按值发送的参数设置新值。为了向函数发送指针或任何变量并让函数更改其值,您应该通过引用发送它,即它的地址。

假设您具有以下功能:

void changePtr(no **ptr) {
*ptr = // .. some value
}
void dontChangePtr(no *ptr) {
ptr = // some value
}

您应该注意到函数调用之间的差异:

no *n = (no*)malloc(sizeof(no));
dontChangePtr(n); // n will be sent by value and will not be changed
changePtr(&n); // n will be sent by reference and will be changed

关于c - 如何从函数返回链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44232116/

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