gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:34:50 24 4
gpt4 key购买 nike

我正在尝试创建一个分配给“列表”开头的临时“迭代器”结构,然后通过检查 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;
}

最佳答案

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

关于c - 分配 struct = struct 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42199609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com