dentzigui said:
Hello, I hope to be clear. Forgive my english and forgive me if this
question is trivial.
struct _data {
struct _data *next;
char *item; };
...
srtuct _data *last;
last->next = (struct _data *) malloc (sizeof (struct _data)); ----> why
this causes a segmentaion fault?
At the time you make this call, last probably doesn't point to a valid
memory location. Here is a piece of code that does what you want
in 2 different ways. Understanding the differences will help.
#include <stdlib.h>
#include <stdio.h>
struct data {
struct data *next;
char *item;
};
void
print_list(struct data *list)
{
printf("%s\n", list->item);
if (list->next != NULL)
print_list(list->next);
}
void *
initialize_entry(char *item)
{
struct data * ret;
ret = malloc(sizeof *ret);
if (ret == NULL) {
perror(NULL);
exit(EXIT_FAILURE);
}
ret->item = item;
ret->next = NULL;
return ret;
}
int
main(void)
{
struct data head_array[1];
struct data *head_ptr;
head_ptr = initialize_entry("First item in the ptr list");
head_ptr->next = initialize_entry("End of ptr list");
head_array->item = "First item in the array.";
head_array->next = initialize_entry("End of array list");
print_list(head_array);
print_list(head_ptr);
return EXIT_SUCCESS;
}