Skip to content

Instantly share code, notes, and snippets.

@grayed
Created March 13, 2024 13:06
Show Gist options
  • Save grayed/28e5f3b2ec495d01f5fdadddde859c65 to your computer and use it in GitHub Desktop.
Save grayed/28e5f3b2ec495d01f5fdadddde859c65 to your computer and use it in GitHub Desktop.
Ptr and ref C++
#include <iostream>
using namespace std;
int ma8in() {
int a = 3, b = 7, c, nums[100] = { 11, 22, 33 };
int *p1 = &a, *p2 = &b, *p3 = &c, *pn = nums;
void *p = p1; p3 = (int*)p;
c = a + b;
cout << "a=" << a << ", b=" << b << ", c=" << c
<< ", *p1=" << *p1 << ", *p2=" << *p2 << ", *p3=" << *p3 << endl;
a = 12;
p1 = p2;
*p1 = *p3;
p1 = 0; p2 = NULL; p3 = nullptr;
if (p1)
cout << "*p1 points to " << *p1 << endl;
else
cout << "p1 is null pointer" << endl;
cout << "a=" << a << ", b=" << b << ", c=" << c
<< ", *p1=" << *p1 << ", *p2=" << *p2 << ", *p3=" << *p3 << endl;
for (int i = 0; i < sizeof(nums)/sizeof(nums[0]); i++)
cout << " " << pn[i];
cout << endl;
return 0;
}
/// Задание 1: сделать калькулятор (ввод двух значений и операции) с вычислением
/// в отдельных функциях через ссылки. Операции: +, -, *, /, логарифм, модуль
/// Задание 2: перейти от ссылок к указателям (N.B.: операции &foo и *pfoo)
int add(const int &x, const int &y) { return x + y; }
void transpose(int &x, int &y) { int t = x; x = y; y = t; }
int main() {
int a = 3, b = 7, c, nums[100] = { 11, 22, 33 };
int *p1, *p2, *p3, *p = nums; void *x = p;
int &ref1 = a, &ref2 = b, &ref3 = c;
ref3 = add(a, b);
transpose(a, b);
cout << "a=" << a << ", b=" << b << ", c=" << c << endl;
if (p1)
cout << "p1 points to " << *p1 << endl;
else
cout << "p1 is null pointer" << endl;
*p1 = 123;
for (int i = 0; i < sizeof(nums)/sizeof(nums[0]); i++)
cout << " " << p[i];
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment