鱼C论坛

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

[已解决]为什么输出不了结果

[复制链接]
发表于 2023-10-24 20:25:22 | 显示全部楼层 |阅读模式

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

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

x
#include<iostream>
#include<string>
using namespace std;
struct student
{
        string name;
        int age;
        int score;
};
int main()
{
        struct student arr[3]={"李四",80,100};
        cout<<arr[3].name<<"  "<<arr[3].age<<"  "<<arr[3].score<<endl;
        return 0;
}
最佳答案
2023-10-24 20:25:53
问题出在数组的索引上。在C++中,数组的索引是从0开始的,所以arr[3]实际上是访问了数组的第4个元素,而数组arr只有3个元素。这会导致访问了一个不存在的内存位置,所以输出结果不正确。

要解决这个问题,可以将数组的大小改为4,或者将索引改为0、1或2。修改后的代码如下:

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. struct student
  5. {
  6.     string name;
  7.     int age;
  8.     int score;
  9. };
  10. int main()
  11. {
  12.     struct student arr[4] = {{"李四", 80, 100}};
  13.     cout << arr[0].name << "  " << arr[0].age << "  " << arr[0].score << endl;
  14.     return 0;
  15. }
复制代码


这样就能正确输出结果了。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-10-24 20:25:53 | 显示全部楼层    本楼为最佳答案   
问题出在数组的索引上。在C++中,数组的索引是从0开始的,所以arr[3]实际上是访问了数组的第4个元素,而数组arr只有3个元素。这会导致访问了一个不存在的内存位置,所以输出结果不正确。

要解决这个问题,可以将数组的大小改为4,或者将索引改为0、1或2。修改后的代码如下:

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. struct student
  5. {
  6.     string name;
  7.     int age;
  8.     int score;
  9. };
  10. int main()
  11. {
  12.     struct student arr[4] = {{"李四", 80, 100}};
  13.     cout << arr[0].name << "  " << arr[0].age << "  " << arr[0].score << endl;
  14.     return 0;
  15. }
复制代码


这样就能正确输出结果了。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-20 20:27

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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