Labels

Android (1) bash (2) boost (2) C (34) C++ (2) cheatsheet (2) CLion (6) css (3) Debian (33) DL (17) Docker (1) Dreamweaver (2) Eclipse (3) fail2ban (4) git (5) GitHub (4) Hacking (3) html (8) http (1) iOS (1) iPad (1) IRC (1) Java (30) javascript (3) Linux (164) Mac (19) Machine Learning (1) mySQL (47) Netbeans (4) Networking (1) Nexus (1) OpenVMS (6) Oracle (1) Pandas (3) php (16) Postgresql (8) Python (9) raid (1) RedHat (14) Samba (2) Slackware (45) SQL (14) svn (1) tar (1) ThinkPad (1) Virtualbox (3) Visual Basic (1) Visual Studio (1) Windows (2)

Wednesday 19 August 2020

C++ Pointers

Some stuff on Pointers (again).




#include <iostream>
using namespace std;

int main()
{
    string name = "Harry";  // Variable declaration
    string* ptr = &name;    // A pointer variable, with the name ptr,
                            // that stores the address of name.
                           
    // The following outputs the name, the address of name,
    // the address with the pointer and the contents of the address the
    // pointer points to. (known as de referencing the pointer).
   
    cout << name << " " << &name << " " << ptr << " " << *ptr << endl;
   
    *ptr = "Hello"; // change the value at the memory location
   
    // The following outputs the contents of the address the pointer
    // points to and also the name, which has been updated via the pointer.
    cout << *ptr << " " << name << endl;

}


Also;

#include <stdio.h>

int main()
{
    int n=5;
    int *ptr =&n;

    printf("Value of n = %d \n",n);
   
    printf("Address of n = %p \n",&n);
   
    printf("The value stored at the address %p is %d \n", &n, *ptr);
   
    printf("Lets now add 1 to n... \n");
   
    *ptr = *ptr +1;

    // *ptr++ doesn't work as expected but (*ptr)++ does.

   
    printf("The value stored at the address %p is %d \n", &n, *ptr);
   
    printf("%d \n",n == *ptr);

    return 0;
}


See also here

The following shows a value being passed as a reference

#include <iostream>
using namespace std;

void doSomething(int&);

int main()
{
    int i = 10;
    cout << i << endl;
    doSomething(i); 
    return 0;
}

void doSomething(int& i)  // receives i as a reference
{
    cout << i << endl;
}


The following shows a value being passed as a pointer

#include <iostream>
using namespace std;

void doSomething(int*);

int main()
{
    int i = 10;
    cout << i << endl;
    doSomething(&i);
}

void doSomething(int* i)
{
     cout << *i << endl;
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.