Здесь .... здесь много неправильного.
Первое, что выскакивает:
struct person *newly;
...
newly[i].name=pname;
newly
- указатель на человека.Вы никогда не выделяете person
, а затем пытаетесь получить к нему доступ, как будто это локальная структура (несколько раз) как ... массив?
struct person *newly = malloc(sizeof(struct person));
- это то, что вы ищете.Затем вы передадите его своей функции insert
:
insert(newly);
new_person
является избыточной и ничего не делает.То же самое с вашим node
Вы также никогда не выделяли заголовок самого списка.Ваш insert
предполагает, что есть голова ... которой там нет.Вы должны установить element
на NULL
и проверить это, потому что если это NULL
... это ваша первая вставка в список.( edit: Хм, ну, на самом деле head
и ... читая это снова, я не уверен, что вы пытаетесь сделать с element
)
Честно говоря - япредложил бы немного googling, или книгу C новичка.Мы можем указать на все проблемы в вашем коде, но без понимания того, что вы на самом деле используете , вы не получите выгоды.
РЕДАКТИРОВАТЬ: С учетом вышесказанного, я думаю, разумно опубликовать рабочий пример, сохранив как можно больше исходного кода.
#include<stdio.h>
#include<stdlib.h>
struct person
{
char *name;
int age;
char *ssn;
};
/* Note: because head and tail are global they
are initialized to NULL automatically */
struct node
{
struct person *person;
struct node *next;
} *head, *tail;
void insert(struct person *new_person)
{
/* allocate a new node */
struct node *node = malloc(sizeof(struct node));
/* assign the person to the node */
node->person = new_person;
node->next = NULL;
if (head == NULL)
{
/* Since head is NULL, we are inserting for the first time.
Set the head and tail to point at our new node */
head = node;
tail = node;
}
else
{
/* the tail is the last node in our list. We attach the new
node to its next, then repoint the tail to our new node */
tail->next = node;
tail = node;
}
}
void display()
{
if(head == NULL)
{
printf("empty list\n");
}
else
{
struct node *current = head;
while(current != NULL)
{
printf("%s %d %s ", current->person->name,
current->person->age,
current->person->ssn);
current = current->next;
if(current != NULL)
printf("->");
}
printf("\n");
}
}
main()
{
int total_no_person,i;
printf("enter the total number of person \t");
scanf("%d",&total_no_person);
for(i=0;i<total_no_person;i++)
{
/* allocate a new person, then allocate its members */
struct person *newly = malloc(sizeof(struct person));
newly->name = malloc(100);
newly->ssn = malloc(100);
printf("enter the %dth person's name \t",i+1);
scanf("%s", newly->name);
printf("enter %dth person's age \t",i+1);
scanf("%d", &newly->age);
printf("enter %dth person's ssn \t",i+1);
scanf("%s", newly->ssn);
insert(newly);
}
display();
}
Одинлишний бит, который я пропустил - это та часть, где вы можете переполнить входной буфер с помощью scanf
- http://www.crasseux.com/books/ctutorial/String-overflows-with-scanf.html