Pointer

mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.9 kB
8
Indexable
Never
#include <iostream>
using namespace std;

// ===================================================
// >> 1. Normal Declare
int main()
{
    // dereference
    string name = "tegar";

    cout << "name : " << name << endl;
    cout << "address name : " << &name << endl;

    // declare
    string *ptrName = &name;
    cout << ptrName << endl;
    cout << *ptrName << endl;
    
    // reassign
    *ptrName = "john";
    cout << ptrName << endl;
    cout << *ptrName << endl;

    // direct reference & dereference
    cout << *&name << endl;

    // diff declare pointer diff address
    string *ptrA = &name;

    *ptrA = "Aldi";
    string *ptrB = ptrA;

    cout << *ptrA << endl;
    cout << *ptrB << endl;
    cout << name << endl;

    // assign pointer into pointer?
    string *ptrC = &*ptrA;
    cout << ptrC << endl;
    cout << *ptrC << endl;

    // combine with operator aritmathic
    int a = 5;
    int *ptrAA = &a;
    *ptrAA += *ptrAA;
    cout << *ptrAA << endl;
}

// >> 2. Array With Pointer
// int main()
// {
//     // 1 dimention
//     int arr[3] = {5,6,8};
//     int *ptrArr = arr;

//     *(ptrArr + 1) = 10;
    
//     cout << ptrArr[1] << endl;
//     cout << arr << endl;
//     cout << *arr << endl;

//     // 2 dimention
//     int arr2[2][3]    = {{10,20,30}, {40, 50, 60}};
//     int (*ptrArr2)[3] = arr2;

//     cout << ptrArr2 << endl;
//     cout << arr2 << endl;
// }

// ===================================================
// >> 3. Pointer On Fuction
// void sum(int *ptrA)
// {
    // cout << "func pointer (address): " << ptrA << endl;
//     cout << "func pointer: " << ptrA << endl;
// }

// int main()
// {
//     int a = 5;
//     int *ptrA = &a;
//     cout << ptrA << endl;
    
//     cout << "pointer (address): " << ptrA << endl;
//     cout << "pointer: " << *ptrA << endl;

//     sum(ptrA);
// }
Leave a Comment