Я пытаюсь создать временную структуру «итератора», которая назначается началу «списка», а затем перебирает этот список структур, проверяя iterator->next != NULL
. Я считаю, что проблема заключается в линиях iterator = start
(35 & 70).Ошибка сегментации при назначении struct = struct
Приложение компилируется без каких-либо проблем, но мне дается ошибка сегментации (ядро сбрасывается), когда приложение ./
.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct record
{
int accountno;
char name[25];
char address[80];
struct record* next;
};
int addRecord (struct record **, int, char [], char []);
void printAllRecords(struct record *);
int main(int argc, char *argv[]) {
struct record ** start;
start = NULL;
addRecord(start, 1, "Record Name", "Record Address");
printAllRecords(*start);
return 0;
}
void printAllRecords(struct record * start)
{
struct record * recordIterator;
/* Allocate the required memory and return a pointer to it */
recordIterator = malloc(sizeof(struct record));
/* Start at the beginning */
recordIterator = start;
printf("\n\n%10s %20s %20s\n", "accountno", "Name", "Address");
while (recordIterator != NULL)
{
printf("%10d %20s %20s\n", recordIterator->accountno, recordIterator->name, recordIterator->address);
recordIterator = recordIterator->next;
}
}
int addRecord (struct record ** start, int accountno, char name[], char address[])
{
struct record * newRecord;
/* Allocate the required memory and return a pointer to it */
newRecord = malloc(sizeof(struct record));
/* Assign values to the new record */
newRecord->accountno = accountno;
strcpy(newRecord->name, name);
strcpy(newRecord->address, address);
if (start == NULL)
{
start = &newRecord;
}
else
{
struct record * recordIterator;
/* Allocate the required memory and return a pointer to it */
recordIterator = malloc(sizeof(struct record));
/* Start at the beginning */
recordIterator = *start;
while (recordIterator->next != NULL)
{
recordIterator = recordIterator->next;
}
recordIterator->next = newRecord;
}
return 1;
}
'start' в' addRecord' является локальной копией. Это изменение не будет отражено после возвращения функции. –
Почему вы динамически выделяете память только для немедленного выброса? Ваша программа утечки памяти ... bad – StoryTeller
Нет причин, по которым 'start' должен быть указателем на указатель в main. Объявите его как простой указатель, затем передайте его адрес функции. – Lundin