【问题标题】:Inserting array of struct into linked list将结构数组插入链表
【发布时间】:2021-01-09 04:25:57
【问题描述】:

我的链表练习要求我创建一个结构数组,其中包含人名(定义为 4 个字符的名称)以及该人与我的距离。

创建 3 个数组元素后,我将每个人和他的距离放入一个链表中。

我已经制作了数组并按原样成功打印了它,但是制作列表时遇到了麻烦。

我的代码如下,非常感谢一个让代码启动并运行的解决方案。

    typedef struct Node
{
    int dist;
    char name[4];
    struct Node* next;
}Node;

void main()
{
    int i;
    Node arr[3];

for (i = 0; i < 3; i++)
{
    printf("Enter name: \n");
    scanf("%s", arr[i].name);

    printf("Enter distance: \n");
    scanf("%d", &arr[i].dist);
}
printf("Basic printing of the ARRAY:");
for (i = 0; i < 3; i++)
{
    printf("Distance of %s is: %d\n", arr[i].name, arr[i].dist);
}

printf("\n\n\n");
Node* head;
Node* tail;
head = tail = NULL;
head = malloc(sizeof(Node));
tail = malloc(sizeof(Node));
for (i = 0; i < 3; i++)
{
    if (i == 0)
    {
    
        head->dist = arr[i].dist;
        head->name[4] = arr[i].name;
        tail = head;
    }
    else
    {
        tail->next = malloc(sizeof(Node));
        tail = tail->next;
        tail->next = NULL;
        tail->dist = arr[i].dist;
        tail->name[4] = arr[i].name;
    }
}
Node* temp;
temp = head;
printf("Now we print the list\n");
for (i = 0; i < 3; i++)
{
    printf("Distance of %s is: %d\n", temp->name, temp->dist);
    temp = temp->next;
}

【问题讨论】:

    标签: arrays c struct linked-list


    【解决方案1】:

    嗯,我找到了解决办法。 将名称输入到列表中时,正确使用的是 strcpy。

    right way:
    strcpy(tail->name, arr[i].name)
    
    wrong way (what I used):
    tail->name[4]=arr[i].name;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      • 2019-03-08
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 2014-12-07
      相关资源
      最近更新 更多