Pour un exercice que je fais sur les pointeurs en C, je veux insérer une structure au début d'une liste chaînée en envoyant le pointeur listStart à la fonction insertEntry avec la structure que je veux insérer . Cependant, avec ce code actuel, je suis incapable de faire cela car le pointeur listStart ne porte pas avec lui l'adresse de ce qu'il pointait dans la fonction principale (la toute première structure de la liste).Envoyer le pointeur de la liste à la fonction
Je comprends que je ne fais que copier le pointeur lui-même dans la fonction insertEntry et donc l'adresse vers laquelle il pointait est omise. Cela signifie que tout ce que j'obtiens du pointeur listStart dans la fonction insertEntry est un pointeur nul.
Pour résoudre ce problème, j'ai essayé d'envoyer le listStart à la fonction insertEntry comme un pointeur, cependant, cela m'a juste donné un pointeur vers un pointeur qui pointe vers null. J'ai essayé d'envoyer l'adresse de listStart à la fonction qui ne fonctionnait pas car elle envoyait null à la fonction.
Les questions que j'ai: est-ce possible de le faire et je manque juste quelque chose? Ou est-ce pas possible?
Merci à l'avance.
// header to include standard input and output
#include <stdio.h>
struct entry
{
int value;
struct entry *next;
};
// prototype for insertEntry function
void insertEntry(struct entry *l, struct entry *i, struct entry *j);
int main(void)
{
// declaration of array for linked list
struct entry list1 = { 1 }, list2 = { 2 }, list3 = { 3 }, list4 = { 4 }, list5 = { 5 }, insert = { 8 };
struct entry *listStart = &list1;
// test to see if the value of the insert.value struct is correct
printf("insert.value = %i\n", insert.value);
// assign pointers in list.next to the next struct in the list to create a linked list
list1.next = &list2;
list2.next = &list3;
list3.next = &list4;
list4.next = &list5;
list5.next = (struct entry *) 0;
// print the linked list to make sure the pointers are going to the correct struct member
printf("Original list!\n");
while (listStart != (struct entry *) 0)
{
printf ("%i\n", listStart->value);
listStart = listStart->next;
}
// send struct to change and struct to insert
insertEntry(listStart, &insert, &list1);
// restart the list from the beginning because in the last while loop the listStart was assigned to the null pointer.
listStart = &list1;
// print the new list to show what has been inserted and moved around
printf("New list!\n");
while (listStart != (struct entry *) 0)
{
printf ("%i\n", listStart->value);
listStart = listStart->next;
}
return 0;
}
// function to insert a new struct in the list and redirect an old struct in the list
void insertEntry(struct entry *l, struct entry *i, struct entry *j)
{
i->next = l; // this is assigning the mem add of the pointer is list2.next to that of insert.next
l = i; // this is assigning the mem add of i which would be insert.value to the pointer in list2.next
}
* facepalm * duh! Merci à tous ceux qui ont répondu! – alucinare