0

Array help

hi, still getting the hand of it but i have a program i created thats outputting the memory location or something but not the data stored there. this should be the link to the program if you want to take a look at it. https://code.sololearn.com/cuxyN03y9n2t/?ref=app //maas--changing that still throws garbage and the [x] worked to store them just fine till i made the array a variable length by moving it. after that it started throwing garbage.

29th Jan 2017, 11:08 PM
david schlemmer
david schlemmer - avatar
3 odpowiedzi
+ 1
for (int i = 0; i<s; i++){ cout << "Enter a number for "<<i+1<<": "; cin >> x; cout<<""<<x<<endl; numbers[x]; //The main problem is here! } you are not assigning array element to any value so it throws garbage values when accessed. So just replace numbers[x] with numbers[i] = x EDIT : for (int i = s; i>0 ; i--){ cout<<"value "<<i<<" = "; cout<<numbers[x]; //problem also lies here cout<<""<<endl; } replace numbers[x] with numbers[i] now it must work fine!
29th Jan 2017, 11:48 PM
Mohammed Maaz
Mohammed Maaz - avatar
0
This is the edited code wich must work fine: #include <iostream> using namespace std; //to start type a number to determine how many slots to fill and hit enter. //type any whole number and enter. //repeat to fill all slots. //example: 5 // : 1 // : 2 // : 3 // : 4 // : 5 //on the bottom the values stored in the array are not being printed. //this has been bugging me for a while. //can anyone leave a comment to help me change it. //i want to output the data stored in the array and not the memory location, i guess? int main(){ int s, x; cout<<"how many players? "; cin>>s; cout<<s<<endl; //i moved the array from the top to here so a value will be assigned to 's' so the array will have a variable length. int numbers[s]; for (int i = 0; i<s; i++){ cout << "Enter a number for "<<i+1<<": "; cin >> x; cout<<""<<x<<endl; numbers[i]=x; } //but when i did that numbers[x] stopped outputting the value and started...this? for (int i = s; i>0 ; i--){ cout<<"value "<<i<<" = "; cout<<numbers[i]; cout<<""<<endl; } //i had all of this set up in a class and array type but i moved it over here to simplify it before 'class'ing it up once more. return 0; }
30th Jan 2017, 12:09 AM
Mohammed Maaz
Mohammed Maaz - avatar
0
Ok, one last thing, an array (lets call it arr) of length n will have elements from arr[0] to arr[n-1], so this: for (int i = s; i>0 ; i--){ cout<<"value "<<i<<" = "; cout<<numbers[i]; cout<<""<<endl; } has to be change to either: [...] cout<<numbers[i-1]; [...] or: for (int i = s - 1; i >= 0; i--) [...] or: for (int i = 0; i < s; i++) [...]
30th Jan 2017, 12:31 AM
Robobrine
Robobrine - avatar