使用双指针将值输入结构的问题

问题描述 投票:0回答:1

我必须在函数中使用双指针,以将元素填充到结构中(函数必须为空)。但它不会打印任何内容。我认为问题出在传递正确的地址,但找不到它。

#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;
}
c pointers double structure
1个回答
0
投票

你想要那个:

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; 
  }
}

否则,您将永远不会保存第一个单元格


0
投票

此代码段

if (fst_position == NULL)
{
    fst_position=temp_new;
    return ;
}

不更改通过引用传递的头指针。

可以通过以下方式定义功能

void addRecords(sNums** head)
{
    while ( *head != NULL ) head = &( *head )->ptr;

    *head = createRecord();
}

仅此而已。只有两个陈述。 :)

© www.soinside.com 2019 - 2024. All rights reserved.