分配struct = struct时出现分段错误

时间:2017-02-13 08:27:00

标签: c struct segmentation-fault

我试图创建一个临时的“迭代器”#39;结构被分配到'列表的开头,然后通过检查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;
}

2 个答案:

答案 0 :(得分:4)

您可以将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的值没有改变(我们无论如何也无法做到......当方法返回时,更改不会反映出来),但是我们正在修改{{1指向。

答案 1 :(得分:2)

这一行

addRecord(start, 1, "Record Name", "Record Address");

不会修改start。因此,当您致电start时,NULL仍为printAllRecords