-1

my input is just normal number and name like "12345", "Joe", but the output got all weird number like -2743443232 and \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;
}
JHBonarius
  • 10,824
  • 3
  • 22
  • 41
newLearner
  • 19
  • 4
  • 2
    Does this answer your question? [How do I use arrays in C++?](https://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c) – rsjaffe Jul 31 '20 at 19:22
  • 1
    pass display(stu) – Thakur Karthik Jul 31 '20 at 19:23
  • 1
    stu[5] is one past the end of the array. see the linked duplicated question for more information – rsjaffe Jul 31 '20 at 19:23
  • `cin>>stu[i].name;` may be part of your problem after you fix `display(&stu[5]);`. Make sure they don't type a first and last name. Remember that if you type a space the part up to the first space goes into the `name` and the rest will be input to the next `Id` – drescherjm Jul 31 '20 at 19:32

2 Answers2

3

The line

display(&stu[5]);

causes undefined behavior. Remember that in an array of size 5, 4 is largest valid index to access the array.

Change it to

display(&stu[0]);

or simply

display(stu);

Re

but if I change to &stu[0], it will ouput same id and name 5 time?

the answer is, yes given your posted code. You need to update display to

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

to display the data corresponding to all the elements of the array.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

This line display(&stu[5]); is causing Undefined Behavior.

You are saying that stu has a 5th index, which it does not.

When you define an array of 5 elements. You only really have an index of 0, 1, 2, 3, 4.

So instead put, display(&stu[0]).

Geno C
  • 1,401
  • 3
  • 11
  • 26