鱼C论坛

 找回密码
 立即注册
查看: 910|回复: 1

[已解决]结构体初始化,

[复制链接]
发表于 2020-12-14 18:27:50 | 显示全部楼层 |阅读模式

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

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

x
这哪有问题,结构体数组初始化
最佳答案
2020-12-14 19:42:07
字符串赋值不能直接name[20]="dingding",应该用strcpy函数
结构体和其他类型基础数据类型一样,例如 int 类型,char 类型 只不过结构体可以做成你想要的数据类型。以方便日后的使用
在定义结构体时不能直接定义成结构体数组,需要先定义结构体,再在程序段中定义结构体数组(类似定义整形数组一样)
提供两种方案
第一种方法
  1. struct Student
  2. {
  3.    int num;
  4.    char name[20];
  5.    float score;
  6. }stu;

  7. int main(void)
  8. {
  9.    Student stu[3];
  10.    
  11.    strcpy(stu[0].name,"liyan"),stu[0].score=90.5;
  12.    strcpy(stu[1].name,"dingding"),stu[1].score=239;
  13.    strcpy(stu[2].name,"xianxian"),stu[2].score=344;

  14.    system("pause");
  15.    return 0;
  16. }
复制代码

第二种方法
  1. struct Student
  2. {
  3.    int num;
  4.    char name[20];
  5.    float score;
  6. }stu;

  7. int main(void)
  8. {
  9.    Student stu[3]={{0,"liyan",90.5},{0,"dingding",239},{0,"xianxian",344}};

  10.    system("pause");
  11.    return 0;
  12. }
复制代码
qq.PNG
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-12-14 19:42:07 | 显示全部楼层    本楼为最佳答案   
字符串赋值不能直接name[20]="dingding",应该用strcpy函数
结构体和其他类型基础数据类型一样,例如 int 类型,char 类型 只不过结构体可以做成你想要的数据类型。以方便日后的使用
在定义结构体时不能直接定义成结构体数组,需要先定义结构体,再在程序段中定义结构体数组(类似定义整形数组一样)
提供两种方案
第一种方法
  1. struct Student
  2. {
  3.    int num;
  4.    char name[20];
  5.    float score;
  6. }stu;

  7. int main(void)
  8. {
  9.    Student stu[3];
  10.    
  11.    strcpy(stu[0].name,"liyan"),stu[0].score=90.5;
  12.    strcpy(stu[1].name,"dingding"),stu[1].score=239;
  13.    strcpy(stu[2].name,"xianxian"),stu[2].score=344;

  14.    system("pause");
  15.    return 0;
  16. }
复制代码

第二种方法
  1. struct Student
  2. {
  3.    int num;
  4.    char name[20];
  5.    float score;
  6. }stu;

  7. int main(void)
  8. {
  9.    Student stu[3]={{0,"liyan",90.5},{0,"dingding",239},{0,"xianxian",344}};

  10.    system("pause");
  11.    return 0;
  12. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-5-8 02:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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