0

Problem With Pointers CPP !

Hello guys ** I have this data from user Exam 1 Exam 2 Exam 3 ... ---------------------------------------------- Student 1: 13 14 15 ---------------------------------------------- Student 2: 18 - - ---------------------------------------------- Student 3: 20 12 - ---------------------------------------------- ** And I want to print the student scores, but the result of my code is: -------------------------------------------------------------- Student[0,0]=20 Student[0,1]=12 Student[0,2]=15 Student[1,0]=20 Student[2,0]=20 Student[2,1]=12 -------------------------------------------------------------- *********** What's wrong with this?? 👇👇👇👇*********** https://code.sololearn.com/c0d35ZZDn1Az/?ref=app

21st Sep 2019, 3:52 PM
Fardin Karimi
Fardin Karimi - avatar
2 RĂ©ponses
+ 2
The problem seems to be that line 53 int c[ exam[ i ] ]; creates an array at the same memory location in every iteration. As a result, every student[ i ] points to the same memory sequence and existing entries are overwritten. Technically, your program shouldn't even compile outside of SoloLearn. Plain arrays require you to define their size at compile time, however, user input is taken in later, at runtime. It works on SoloLearn because all input is acquired before the program is run, but this method won't work in actual compilers. Basically, you have two ways of fixing this problem. Number one is to use dynamically allocated memory with new[] and delete[]. It allows you to set up the array size at runtime, and, since you request the memory by yourself, the memory location won't be the same in every iteration. Number two is to use vectors from the standard template library. They are essentially dynamically allocated arrays, but the class will handle all the responsibilities for you.
21st Sep 2019, 6:28 PM
Shadow
Shadow - avatar
+ 1
I used new[] and delete[] and my problem was completely solved. Thank you so much. https://code.sololearn.com/c9nRLzTeOg3v
21st Sep 2019, 7:49 PM
Fardin Karimi
Fardin Karimi - avatar