linked lists, how to swap pointers through functions?

Question:

The insert_end function receives a pointer to a linear linked list and adds values ​​passed by value to the end of said list. The problem is when the list passed has zero components, that is, the pointer to the first component of the list points to NULL. The function stops working; What you should do is create a new structure, put the corresponding value, enter a NULL (in the corresponding field, since it is used as a completion criterion) so that the list ends there and make the pointer that pointed to the list (which initially -in this case- pointed to NULL) point to this new dynamically created structure , it is this last part that I think I misspelled. I attach the code. Thank you.

#include <stdio.h>
#include <stdlib.h>
#define cant 3
struct nodo {
             int dato;
             struct nodo* sig;
            };
void mostrar(struct nodo*);
void insertar_final(struct nodo*,int);

main()
{
 int i,d;
 struct nodo *l=NULL;
  printf("Ingrese un valor\t");      //inserto un solo valor al final de la lista
  scanf("%d",&d);
  insertar_final(l,d);
 mostrar(l);
 return 0;
}
void insertar_final(struct nodo *l,int d)
{                                                                                                                                 
 struct nodo *temp;
 temp=(struct nodo*)malloc(sizeof(l));
 temp->dato=d;
 if(l==NULL)
  {
  temp->sig=NULL;
  l=temp;
  return;
  }

 while(l->sig!=NULL)
 {
  l=l->sig;
 }
 l->sig=temp;
 temp->sig=NULL;
}

Answer:

In C ALL parameters are passed by value

The pointers too.

So when you run insertar_final(l,d); function insertar_final receives a copy of l . Modifications that the function makes to the l parameter do not affect the l variable of main.

l in insertar_final is a pointer that points to a memory area reserved with malloc The changes we make in that memory area do affect main (and the entire program). Because the call to a function only copies the parameters, it does not copy the memory areas pointed to by those parameters.

If we want the value of the variable l located in main to be changed from insertar_final we cannot pass l . What we must do is to pass a pointer to l (which would be a pointer to pointer to struct node).

This would be the code for insertar_final :

void insertar_final(struct nodo **pl,int d)
{
 struct nodo *temp;
 temp=(struct nodo*)malloc(sizeof(*pl));
 temp->dato=d;
 if(*pl==NULL)
  {
  temp->sig=NULL;
  *pl=temp;
  return;
  }

 struct nodo* l = *pl;
 while(l->sig!=NULL)
 {
  l=l->sig;
 }
 l->sig=temp;
 temp->sig=NULL;
}

Which we would call with

insertar_final(&l,d);    // AMPERSAND para pasar un puntero a l
Scroll to Top