我必须在函数中使用双指针,以将元素填充到结构中(函数必须为空)。但它不会打印任何内容。我认为问题出在传递正确的地址,但找不到它。
#include <stdio.h>
#include <stdlib.h>
typedef struct nums{
int num;
struct nums *ptr;
}sNums;
void addRecords(sNums** head);
sNums* createRecord();
void prinrecords(sNums* head);
int main(int argc, char const *argv[])
{
sNums* head=NULL;
printf("%d\n", &head);
for (int i = 0; i < 3; ++i)
{
addRecords(&head);
}
system ("pause");
}
void prinrecords(sNums* head){
while(head!=NULL){
printf("{%d} ", head->num);
head=head->ptr;
}
}
void addRecords(sNums** head){
sNums* temp_new=createRecord();
sNums* fst_position;
fst_position=*head;
printf("%d\n", fst_position);
if (fst_position == NULL)
{
fst_position=temp_new;
return ;
}
while(fst_position->ptr!=NULL){
fst_position=fst_position->ptr;
}
fst_position->ptr=temp_new;
}
sNums* createRecord(){
sNums *new=(sNums*)malloc(sizeof(sNums));
printf("Enter Number: ");
scanf("%d", &new->num);
new->ptr=NULL;
return new;
}
你想要那个:
void addRecords(sNums** head){
sNums* temp_new=createRecord();
if (*head == NULL)
*head = temp_new;
else {
sNums* fst_position = *head;
while(fst_position->ptr!=NULL){
fst_position=fst_position->ptr;
}
fst_position->ptr=temp_new;
}
}
否则,您将永远不会保存第一个单元格
此代码段
if (fst_position == NULL)
{
fst_position=temp_new;
return ;
}
不更改通过引用传递的头指针。
可以通过以下方式定义功能
void addRecords(sNums** head)
{
while ( *head != NULL ) head = &( *head )->ptr;
*head = createRecord();
}
仅此而已。只有两个陈述。 :)