J'essaye d'implémenter la structure de données de liste liée pour mon cours de collège, mais en exécutant le code la ligne suivante produit une erreur EXC_BAD_ACCESS (code = 1, adresse = 0x8).malloc() provoquant l'erreur EXC_BAD_ACCESS dans Xcode
temp->next = (ptrtonode) malloc(sizeof(struct node));
Voici le code dans son intégralité.
#include <stdio.h>
#include <stdlib.h>
typedef struct node *ptrtonode;
typedef ptrtonode header;
struct node
{
int data;
ptrtonode next;
};
ptrtonode create(int n)
{
int i;
header temphead = NULL;
ptrtonode temp = temphead;
for(i=0;i<n;i++)
{
temp->next = (ptrtonode) malloc(sizeof(struct node));
printf("Enter data for node %d: ", i+1);
scanf("%d", &temp->next->data);
temp = temp->next;
}
temp->next = NULL;
return temphead;
}
int main(int argc, const char * argv[])
{
header head;
int n;
printf("How many nodes do you wish to create?");
scanf("%d", &n);
head = create(n);
}
Toute aide serait appréciée. Merci à tous!
Si '' temphead' n'est pas null', puis au cours de la Attribution 'temp = temphead', Xcode crache un avertissement: _Variable 'temphead' n'est pas initialisé lorsqu'il est utilisé ici et le programme s'arrête sur la ligne' malloc() '. Dit 'Thread 1: breakpoint 1.1' Je ne comprends pas. Cela semble fonctionner à Fedora au collège. Que fais-je incorrectement maintenant? Oh, et j'ai implémenté vos autres points aussi. – vigneshwerv
Peu importe, j'ai alloué de la mémoire à 'temphead' avant de faire l'affectation' temp = temphead'. Le programme fonctionne très bien maintenant. Je vous remercie. – vigneshwerv