C语言链表,哪里错了?

哪里错了

#include<stdio.h>
#include<stdlib.h>
struct student {
    int num;
    char name[20];
    struct student *next;
};
struct student *crea(int n)
{
    int i;
    struct student *head, *p_end, *p_new;//p_new指向链表新的结点,end指向最后一个结点,head是头节点
    head = NULL;
    for (i = 0; i < n; i++)
    {
        p_new = (struct student*)malloc(sizeof(struct student));//循环分配内存空间
        if (p_new == NULL)
        {
            printf("第%d个学生分配内存空间失败!", i + 1);
            break;
        }
    }
    printf("输入第%d个学生的学号:",i+1);
    scanf_s("%d", &p_new->num);
    printf("输入第%d个学生的姓名:", i + 1);
    scanf_s("%s", p_new->name,sizeof(p_new->name));
    return head;
}
int main()
{
    struct student*head = crea(0);
    system("pause");
    return 0;
}

图片描述

阅读 1.6k
1 个回答

C4101 警告指示变量未使用。

以下是参考代码,望仔细对比,亲手练习才有益

// 使用 c11 标准编译。
#include <stdio.h>
#include <stdlib.h>

struct student {
  int num;
  char name[20];
  struct student *next;
};

struct student *crea(int n) {
  struct student *head = NULL, *end = NULL;
  for (int i = 0; i < n; i++) {
    struct student *p_new =
        (struct student *)malloc(sizeof(struct student)); //循环分配内存空间
    if (p_new == NULL) {
      printf("第%d个学生分配内存空间失败!", i + 1);
      break;
    }
    printf("输入第%d个学生的学号:", i + 1);
    scanf("%d", &p_new->num);
    printf("输入第%d个学生的姓名:", i + 1);
    scanf("%s", p_new->name);

    p_new->next = NULL;
    if (!head)
      head = p_new;
    if (end)
      end->next = p_new;
    else
      end = p_new;
  }
  return head;
}

void print(const struct student *link) {
    const struct student *curr = link;
    int i = 0;
    while (curr) {
        printf("#%d: %s, %d\n", ++i, curr->name, curr->num);
        curr = curr->next;
    }
}

int main() {
  struct student *link = crea(2);
  print(link);
  system("pause");
  return 0;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进