MeowMoo 发表于 2021-1-19 17:43:04

关于结构体变量的问题

前面这两种结构体类型指针定义是一样的吗,都是定义他们为首地址,如果不一样第二种定义是什么意思?如果一样为什么我最下面那段代码老是报错呢,求指教。
struct student
{
        int num;
        float score;
        struct student *next;
}stu,p1,p2;
struct student *stu,*p1,*p2;


struct student
{
        int num;
        float score;
        struct student *next;
}*stu,*p1,*p2;



#include <stdio.h>
#if(1)
struct object
        {
                float Chinese;
                float Math;
                float English;
        }obj;
#endif
struct student
        {
                int num;
                char *name;
                struct object obj;
        }*stu;
int main(void)
{
        void print(struct student *p);
        struct student *stu;
        *stu={8,"JJ Lin",{98.5,90.0,95.5}};
        print(stu);
}

void print(struct student *p)
{
        printf("num         :%d\n",(*p).num);
        printf("name          :%s\n",(*p).name);
        printf("Chinese score :%.1f\n",(*p).obj.Chinese);
        printf("Math score    :%.1f\n",p->obj.Math);
        printf("English score :%.1f\n",p->obj.English);
}

jackz007 发表于 2021-1-19 18:05:36

本帖最后由 jackz007 于 2021-1-19 18:11 编辑

struct student
{
      int num;
      float score;
      struct student * next ;
}stu , p1 , p2                ;
struct student * stu , * p1 , * p2 ; // 错误,相同的变量被重复定义

struct student
{
      int num;
      float score;
      struct student * next ;
} * stu ,* p1 ,* p2         ; // 所有变量定义正确有效

#include <stdio.h>
#if(1)
struct object
      {
                float Chinese   ;
                float Math      ;
                float English   ;
} obj                           ;
#endif
struct student
      {
                int num         ;
                char name   ;// name 需要实质性保存字符串,所以,不可以定义成指针
                struct object obj ;
} * stu                           ;

int main(void)
{
      void print(struct student * p)                     ;
      struct student stu = {8,"JJ Lin",{98.5,90.0,95.5}} ; // stu 需要保存数据,不可以定义成指针,结构整体赋值只能在定义时进行
      print(& stu)                                       ;
}

void print(struct student *p)
{
      printf("num         :%d\n",(*p).num);
      printf("name          :%s\n",(*p).name);
      printf("Chinese score :%.1f\n",(*p).obj.Chinese);
      printf("Math score    :%.1f\n",p->obj.Math);
      printf("English score :%.1f\n",p->obj.English);
}

MeowMoo 发表于 2021-1-20 09:05:49

jackz007 发表于 2021-1-19 18:05


大佬,再问一下,、那下面这两个是一个意思吗,结构体变量名不是表示地址吗,那定义的结构体指针变量的变量名表示啥?
struct student
{
      int num;
      float score;
      struct student * next ;
}stu , p1 , p2
struct student
{
      int num;
      float score;
      struct student * next ;
} * stu ,* p1 ,* p2
页: [1]
查看完整版本: 关于结构体变量的问题