c++ - C++ 得到 -243030403 和 \300\371 数字
问题描述
我的输入只是普通的数字和名称,如“12345”、“Joe”,但输出得到了所有奇怪的数字,如 -2743443232 和 \300\230\340,
using namespace std;
struct student{
int Id;
string name;
};
void display(student *x){
int i;
for( i=0; i<5; i++){
cout<<"student id : "<<x->Id<<endl;
cout<<"student name : "<<x->name<<endl;
}
}
int main(){
student stu[5];
int i;
for( i=0; i<5; i++){
cout<<"enter the student id ";
cin>>stu[i].Id;
cout<<"enter the name of student : ";
cin>>stu[i].name;
}
display(&stu[5]);
return 0;
}
解决方案
线
display(&stu[5]);
导致未定义的行为。请记住,在大小为 的数组中5
,4
是访问该数组的最大有效索引。
将其更改为
display(&stu[0]);
或者干脆
display(stu);
回覆
但如果我改为
&stu[0]
,它会输出相同的 id 和 name 5 次?
答案是,是的,因为您发布了代码。你需要更新display
到
void display(student *x){
int i;
for( i=0; i<5; i++){
cout << "student id : " << x[i].Id << endl;
cout << "student name : " << x[i].name << endl;
}
}
显示与数组的所有元素对应的数据。
推荐阅读
- sql-server - SQL Server:表的行级安全性未在另一个谓词函数中强制执行
- python-3.x - Scrapu-Splash 返回 502 或 504 状态
- python - 如何用一系列连续数字替换熊猫数据框中的列值?
- c++ - /usr/include/x86_64-linux-gnu/bits/string_fortified.h:106:10: 错误:'__builtin_strncpy'
- python - 生成非常具体的向量
- python - 机器人框架 - 获取变量
- python - win32com.client 发送不同的附件而不是固定的文件路径
- python - 在递归中使用和不使用'return'调用函数有什么区别?
- python - 如何在kivy的gridLayout中更改特定按钮的颜色
- ssl - 是否可以有没有主机名的入口 tls?