|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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;
}
问题出在数组的索引上。在C++中,数组的索引是从0开始的,所以arr[3]实际上是访问了数组的第4个元素,而数组arr只有3个元素。这会导致访问了一个不存在的内存位置,所以输出结果不正确。
要解决这个问题,可以将数组的大小改为4,或者将索引改为0、1或2。修改后的代码如下:
- #include<iostream>
- #include<string>
- using namespace std;
- struct student
- {
- string name;
- int age;
- int score;
- };
- int main()
- {
- struct student arr[4] = {{"李四", 80, 100}};
- cout << arr[0].name << " " << arr[0].age << " " << arr[0].score << endl;
- return 0;
- }
复制代码
这样就能正确输出结果了。
|
|