我必须在函数中使用双指针来将元素填充到结构中(函数必须为 void)。但它不打印任何东西。我认为问题在于传递正确的地址但找不到它。
#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;
}