我正在尝试创建一个临时的"迭代器"结构,该结构被分配给"列表"的开头,然后通过检查iterator->next != NULL
遍历该结构列表。我相信问题出在iterator = start
行(35和70(。
应用程序编译没有任何问题,但是当我./
应用程序时,我得到了分段错误(核心转储(。
#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("nn%10s %20s %20sn", "accountno", "Name", "Address");
while (recordIterator != NULL)
{
printf("%10d %20s %20sn", 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
声明为指针,如
struct record * start;
然后你可以通过addRecord(&start, ...)
调用该方法。
方法内部:
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;
}
在函数中传递指针时,请记住,您可以永久修改的是占用地址的值,而不是地址本身。在修改后的版本中,start
的值没有改变(无论如何我们都做不到......更改不会在方法返回时反映出来(,但是我们正在修改start
指向的值。
此行
addRecord(start, 1, "Record Name", "Record Address");
不会修改start
.因此,当您调用printAllRecords
时,start
仍然NULL
。