Passing a pointer (memory address) to a function C++ code sample
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows 2003 Server Standard Edition
Header file: Standard
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Passing pointers to a function, modify the data, return the pointer to main() in C++ programming
To show: How to pass data to a function using a pointer, modify the data and return to main() in C++ programming
// illustrates sending to a function memory address of variable and then modify the content
#include <iostream>
using namespace std;
void main(void)
{
int x = 4, y = 7;
// function prototype
void addcon(int*, int*);
cout<<"\nInitial value of x = "<<x;
cout<<"\nInitial value of y = "<<y;
cout<<"\nThen calls function addcon()\n";
cout<<"\nBringing along the &x = "<<&x<<endl;
cout<<"and &y = "<<&y<<"\n";
cout;
// function call, address of x any y are passed to addcon()
addcon(&x, &y);
cout<<"\nAdd 10...";
cout<<"\nNew value of x = "<<x;
cout<<"\nminus 10...";
cout<<"\nNew value of y = "<<y<<endl;
}
// function definition, parameters are pointers...
void addcon(int *px, int *py)
{
// adds 10 to the data stored in memory pointed to by px
*px = *px + 10;
// minus 10 to the data stored in memory pointed to by py
*py = *py - 10;
}
Output example:
Initial value of x = 4
Initial value of y = 7
Then calls function addcon()
Bringing along the &x = 0012FF60
and &y = 0012FF54
Add 10...
New value of x = 14
minus 10...
New value of y = -3
Press any key to continue . . .