我正在尝试创建一个临时的“迭代器”结构,该结构被分配到“列表”的开头,然后通过检查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("\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;
}发布于 2017-02-13 08:40:40
可以将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指向的值。
发布于 2017-02-13 08:31:47
这条线
addRecord(start, 1, "Record Name", "Record Address");不会修改start。因此,当您调用start时,printAllRecords仍然是printAllRecords。
https://stackoverflow.com/questions/42199609
复制相似问题