Я хочу сохранить начало связанного списка в коде ниже. Я не думаю, что у моего кода есть какие-то проблемы, но когда я добавляю два узла и звоню print
, он покажет мне первое имя второго узла.Сохраните начало связанного списка при добавлении
РЕДАКТИРОВКА: НИКАКАЯ НЕТ НИЧЕГО! Пуст
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct node {
char Number[10];
char FirstName[10];
char LastName[10];
char FatherName[10];
char Email[20];
char SiteName[30];
struct node *next;
};
void print(struct node* list)
{
printf("print1");
printf(list->FirstName);
printf("print2");
}
void addNode(struct node *head)
{
struct node *current = head;
puts("*******Now you can insert a new person****");
struct node *newNode = malloc(sizeof(struct node));
printf("FIRSTNAME: ");
gets(newNode->FirstName);
printf("LASTNAME: ");
gets(newNode->LastName);
printf("FATHERNAME: ");
gets(newNode->FatherName);
printf("EMAIL: ");
gets(newNode->Email);
printf("SITENAME: ");
gets(newNode->SiteName);
//create new node
newNode->next = 0; // Change 1
//check for first insertion
if(current->next == 0){
current->next = newNode;
printf("added at beginning\n");
}
else
{
//else loop through the list and find the last
//node, insert next to it
while (current->next != 0) {
current = current->next;
}
current->next = newNode;
printf("added later\n");
}
}
//*************************************************************************
int main()
{
/* This won't change, or we would lose the list in memory */
struct node *root;
/* This will point to each node as it traverses the list */
struct node *conductor;
root = malloc(sizeof(struct node));
root->next = 0;
addNode(root);
addNode(root);
conductor = root;
//*********************************
print(root);
if (conductor != 0) {
while (conductor->next != 0)
{
conductor = conductor->next;
}
}
/* Creates a node at the end of the list */
conductor->next = malloc(sizeof(struct node));
conductor = conductor->next;
if (conductor == 0)
{
printf("Out of memory");
return 0;
}
/* initialize the new memory */
conductor = root;
if (conductor != 0) {
/* Makes sure there is a place to start */
while (conductor->next != 0) {
puts(conductor->FirstName);
puts(conductor->LastName);
conductor = conductor->next;
}
puts(conductor->FirstName);
}
return 0;
}
Спасибо, да, они определены как char [], я не знаю, что я должен делать именно так? – Nickool
@nikparsa: 'fgets (newNode-> FirstName, sizeof (newNode-> FirstName), stdin);', так что в буфер не считывается больше 'char', чем размер массива. Поскольку 'newNode-> FirstName' является массивом, а не указателем, вы можете использовать' sizeof' для получения размера массива. – AusCBloke
ничего мне не меняет код из get (current-> FirstName); к тому, что вы мне сказали, а также i malloc newnode first – Nickool