символы в связанном списке - PullRequest
1 голос
/ 12 сентября 2011

Я пытаюсь создать связанный список, который будет принимать пользовательские name, age и ssn числа в качестве входных данных и печатать выходные данные в формате списка. Я получаю некоторые ошибки, поэтому не могу получить [input?].

#include <stdio.h>
#include <stdlib.h>

struct person
{
    char *name;
    int age;
    char *ssn;
};

struct node
{
    struct person * person;
    struct node * next;
} *head, *element;

void insert (struct person *new_person)
{
    element->person = new_person;
    element->next = head;
    head = element;
}

void display (struct node *ll)
{
    if(ll == NULL)
        printf("empty list");

    while(ll != NULL)
    {
        printf("%s %d  %s ", ll->person->name, ll->person->age, ll->person->ssn);
        ll = ll->next;

        if(ll != NULL)
            printf("->");
    }
}

main()
{
    int total_no_person, i, page;

    printf("enter the total number of person \t");
    scanf("%d", &total_no_person);

    struct node * temp = (struct node *) malloc(sizeof(struct node));
    struct person * new_person;

    char *pname = NULL;
    char *pssn = NULL;

    head = NULL;

    for(i = 0; i < total_no_person; i++)
    {
        pname = (char *) malloc(100);
        pssn = (char *) malloc(100);

        struct person * newly;

        printf("enter the %dth person's name \t", i + 1);
        scanf("%s", &pname);
        newly[i].name = pname;

        printf("enter %dth person's age \t", i + 1);
        scanf("%d", &page);
        newly[i].age = page;

        printf("enter %dth person's ssn \t", i + 1);
        scanf("%s", &pssn);
        newly[i].ssn = pssn;

        new_person = newly;
        insert(new_person);
    }
    temp = head;
    display(temp);

}

Ответы [ 3 ]

3 голосов
/ 12 сентября 2011

Здесь .... здесь много неправильного.

Первое, что выскакивает:

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

2 голосов
/ 12 сентября 2011

scanf принимает указатель на символ, а не char**:

scanf("%s", pname);

Вы ошибочно берете адрес символ-указатель pname, когда пишете &pname.

2 голосов
/ 12 сентября 2011

Ваш element узел всегда один и тот же, вы никогда не выделяете новый, эффективно перезаписывая одно и то же снова и снова ..

Конечно, это глобальная переменная, поэтому указатель инициализируется значением NULL, поэтому он падает при первой записи.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...