Skip to content

Instantly share code, notes, and snippets.

@chirag-chhajed
Last active September 24, 2023 14:16
Show Gist options
  • Save chirag-chhajed/f55fe05b907313373a2c14de9017971b to your computer and use it in GitHub Desktop.
Save chirag-chhajed/f55fe05b907313373a2c14de9017971b to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// & returns the memory address of that variable.
cout << &x << endl;
// When used in a variable declaration, * denotes a pointer variable. For example:
int *xptr = &x;
// xptr now contains the address of x
cout << xptr << endl;
// To access the value of x, it uses the dereference operator
cout << *xptr << endl;
int y = 10;
int &z = y;
cout << &y << endl;
cout << &z << endl;
// z is a reference variable; y and z share the same memory address. Changing either of them changes both of them.
int value = 42;
int *ptrToValue = &value;
int **ptrToPtr = &ptrToValue; // Pointer to a pointer
cout << &value << endl; // Memory address of value
cout << ptrToValue << endl; // Memory address stored in ptrToValue (same as &value)
cout << *ptrToPtr << endl; // Value of ptrToValue (points to value)
cout << **ptrToPtr << endl; // Value of valuerm
return 0;
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// & returns the memory address of that variable.
cout << &x << endl;
// When used in a variable declaration, * denotes a pointer variable. For example:
int *xptr = &x;
// xptr now contains the address of x
cout << xptr << endl;
// To access the value of x, it uses the dereference operator
cout << *xptr << endl;
int y = 10;
int &z = y;
cout << &y << endl;
cout << &z << endl;
// z is a reference variable; y and z share the same memory address. Changing either of them changes both of them.
int value = 42;
int *ptrToValue = &value;
int **ptrToPtr = &ptrToValue; // Pointer to a pointer
cout << &value << endl; // Memory address of value
cout << ptrToValue << endl; // Memory address stored in ptrToValue (same as &value)
cout << *ptrToPtr << endl; // Value of ptrToValue (points to value)
cout << **ptrToPtr << endl
<< endl; // Value of valuerm
int arr[5] = {1, 2, 3, 4, 5};
int *arrPtr = arr; // Pointer to the first element of the array
cout << arr << endl; // Memory address of the array (same as &arr[0])
cout << arrPtr << endl; // Memory address stored in arrPtr (same as &arr[0])
cout << arrPtr << endl << endl; // Memory address stored in arrPtr (same as &arr[0])
// Using a pointer to iterate through the array
for (int i = 0; i < 5; i++)
{
cout << *(arrPtr + i) << " "; // Dereference arrPtr to access elements
}
cout << endl;
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment