首页 > 解决方案 > 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;
}

标签: c++arrays

解决方案


线

display(&stu[5]);

导致未定义的行为。请记住,在大小为 的数组中54是访问该数组的最大有效索引。

将其更改为

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;
    }
}

显示与数组的所有元素对应的数据。


推荐阅读