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.