Problem with pointers | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Problem with pointers

i wanted to create a classroom exchange program using numbers as student and using pointers . i wrote this code wich seems to me correct but when i run it and give values to a and b . i still find them in their first classroom (c1 or c2) i don't know where the problem is , Here's the code : #include <iostream> using namespace std; int main() { int c1[] = {1,2,3,4}; int c2[] = {5,6,7,8}; int *p1; int *p2; int e,f; //exchange way int a,b; cout << "Choose 2 students to exchange between class 1 and class 2" << endl; cin >> a >> b ; p1 = &c1[a] ; p2 = &c2[b] ; cout <<"The students are : " << *p1 << " and " << *p2 << endl; e=*p1 ; f=*p2 ; c1[a] = f ; c2[b] = e ; cout << " Now student : " << c1[a] << " is in clss 2" << endl; cout << "And student : " << c2[b] << " is in class 1" << endl; return.0; }

16th Dec 2018, 1:51 PM
SIMO
SIMO - avatar
2 Answers
+ 3
Yes, Shadow is right! At the beginning for example c1[0] = 1 is in class 1 (that is c1) and c2[0] = 5 is in class 2 (that is c2), then lets say you want to swap them, so go through all code and c1[0] = 1 becomes c1[0] = 5 and so c2[0] = 5 becomes c2[0] = 1, so the values are swapped, but then you say: cout << “Now student: “ << c1[0] << is in class 2; But since you swapped the values c1[0] now is = 5! Besides c1 is the class 1 so if you call a student from class 1 he is not in class 2 😉 You should say: cour << “The student: “ << c2[0] << is now in class 2😊
16th Dec 2018, 3:24 PM
Sekiro
Sekiro - avatar
+ 4
Ehm, I am *pretty* sure that the values are actually swapped, look at your output instead. You changed the two values a second ago, then you can't refer to them in their old arrays afterwards. c1[a] now holds the swapped value, but you say it is still in class 2, which is not true, because it is in c1. So the problem is not the actual swapping process.
16th Dec 2018, 2:58 PM
Shadow
Shadow - avatar