鱼C论坛

 找回密码
 立即注册
查看: 2058|回复: 4

C语言 定义结构体类型函数的问题

[复制链接]
发表于 2016-3-26 21:02:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 shuofxz 于 2016-3-27 22:25 编辑

下面的代码是将输入的学号和成绩建立链表,并最终输出
代码可以运行,我想问的是:
struct student *creat()   为什么函数名前面要加*,有什么作用?

  1. #include "stdio.h"
  2. #include "malloc.h"
  3. #define NODE struct student
  4. struct student{
  5.         int num;
  6.         float score;
  7.         struct student *next;
  8. };

  9. struct student *creat(){
  10.         NODE *p, *q, *head;
  11.         p = q = (NODE*)malloc(sizeof(NODE));
  12.         head = NULL;
  13.         int n = 0;
  14.         printf("请输入学号:");
  15.         scanf("%d",&(p->num));
  16.         while(p->num)
  17.         {
  18.                 printf("请输入成绩:");
  19.                 scanf("%f", &(p->score));
  20.                 printf("\n");
  21.                 if(n == 0){
  22.                         head = p;
  23.                         n += 1;
  24.                 }
  25.                 else{
  26.                         q->next = p;
  27.                 }
  28.                 q = p;
  29.                 p = (NODE*)malloc(sizeof(NODE));
  30.                 printf("请输入学号:");
  31.                 scanf("%d",&(p->num));               
  32.         }
  33.         q->next = NULL;
  34.         return head;
  35. }

  36. void print(NODE *head){
  37.         NODE *p;
  38.         p = head;       
  39.         while(p)
  40.         {
  41.                 printf("%d \t %3.1f\n", p->num, p->score);
  42.                 p = p->next;
  43.         }
  44. }

  45. int main(){
  46.         struct student *stu;
  47.         stu = creat();
  48.         print(stu);
  49.         return 0;
  50. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-3-26 23:18:46 | 显示全部楼层
struct student *creat() ,实际上就是 student* creat();
就是一个函数声明,最好不要加struct,好理解。
加*表示函数的返回值的类型,是指向student这个结构体的指针啊
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-3-27 22:22:04 | 显示全部楼层
struct student *creat()  加*标识返回的是struct student 结构的一个地址,地址是在子函数里申请的,不然你的head出不来 ,也可以用函数参数传进去也是可以的!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-3-27 22:24:51 | 显示全部楼层
muyu0096 发表于 2016-3-26 23:18
struct student *creat() ,实际上就是 student* creat();
就是一个函数声明,最好不要加struct,好理解。 ...

谢谢,明白了~
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-3-27 22:25:17 | 显示全部楼层
好多好多鱼 发表于 2016-3-27 22:22
struct student *creat()  加*标识返回的是struct student 结构的一个地址,地址是在子函数里申请的,不然 ...

谢谢~
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-22 04:04

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表