【发布时间】:2017-03-02 08:59:42
【问题描述】:
我在理解 C 双指针概念时遇到了麻烦。本质上,我正在尝试编写代码来检查 record_1 是否尚未设置。如果没有,请设置它。如果已设置,我们将在第一条记录.next 指针中添加一个新的struct record newRecord。
我使用的是双指针,因为它是教授要求的
我尝试使用 firstRecord = malloc(sizeof(struct record*)); 没有任何运气,并尝试取消引用 firstRecord。
遍历位于addRecord 函数中的记录的while 循环也无法按预期工作,因为我不知道如何处理双指针。
struct record
{
int accountno;
char name[25];
char address[80];
struct record* next;
};
int addRecord (struct record ** firstRecord, int accountno, char name[], char address[])
{
if (firstRecord == NULL)
{
// Segmentation Fault here
// (*firstRecord)->accountno = accountno;
// Assign the name to the newRecord
// strcpy((*firstRecord)->name, name);
// Assign the name to the newRecord
// strcpy((*firstRecord)->address, address);
// Initialize the next record to NULL
// (*firstRecord)->next = NULL;
}
else
{
// Define a new struct record pointer named newRecord
struct record newRecord;
// Assign the accountno of newRecord
newRecord.accountno = accountno;
// Assign the name to the newRecord
strcpy(newRecord.name, name);
// Assign the address to the newRecord
strcpy(newRecord.address, address);
// Initialize the next record to NULL
newRecord.next = NULL;
// Create a new record and add it to the end of the database
struct record ** iterator = firstRecord;
// Iterate through the records until we reach the end
while (iterator != NULL)
{
// Advance to the next record
*iterator = (*iterator)->next;
}
// Assign the address of newRecord to the iterator.next property
(*iterator)->next = &newRecord;
}
return 1;
}
int main() {
struct record ** firstRecord;
firstRecord = NULL;
addRecord(firstRecord, 1, "Foo", "Bar");
addRecord(firstRecord, 2, "Foo", "Bar");
return 0;
}
【问题讨论】:
-
那么您的具体问题是什么?你试过做什么? (显示的代码实际上并没有做任何事情)
-
你问是因为你试图编写一个函数来做到这一点,有没有机会?你用指针的地址来调用它?
-
根据经验:如果您不了解某些内容,请不要使用它。此代码中绝对不需要指针到指针。因此,您对它的理解问题可能源于这样一个事实:在这里使用它没有任何意义。
-
这里不需要双指针。
-
如果使用的是链表数据结构,则不需要使用双指针。
标签: c pointers struct pointer-to-pointer