c++ - Why wouldn't this program change anything, but the one below it does? -
i'm studying pointers in c++ upcoming exam , don't know why first code here doesn't swap values second 1 does. if explain me why great.
why wouldn't program swap values of b[0] , b[1]:
#include <iostream> using namespace std; void func1 (int* x, int *y) { int* temp = x; x = y; y = temp; } int main() { int b[6] = { 1, 2, 3, 4, 5, 6}; func1(&b[0], &b[1]); cout << b[0] << b[1]; }
but 1 does:
#include <iostream> using namespace std; void func2(int* x, int *y) { int temp = *x; *x = *b; *y = temp; } int main() { int b[6] = { 1, 2, 3, 4, 5, 6}; func2(&b[0], &b[1]); cout << b[0] << b[1]; }
thank :d
the explanation in first case exchanging pointers values, not pointed values themselves. you're manipulating addresses in first case, while in second case, manipulate values.
Comments
Post a Comment