Tuesday, 25 June 2013

source code: Pass by Value and Pass by Reference (pointer array) using C++ [ shown either way ;) ]

#include<iostream>
using namespace std;

class ptrcls{
public:
ptrcls()
{
int length;
cout <<"length of the array?\nans:"; cin>> length;

int numbers[100];

cout <<"\nfill up the array:";
for(int x=0; x<length; x++)
{
cin>> numbers[x];
}

int* ptr; 
// Declaring a pointer with the same data type as integar array.
   
ptr= numbers;
// Assigning the numbers' address of array to pointer, no need of "&" before the numbers
// since the "numbers" array already starts at the first memory location.

cout << "\nPassing an array using a pointer as reference:\n";
cout <<"ptr: ";
for(int i=0; i<length; i++)
{
cout <<*ptr <<", ";
ptr++;
}
cout <<endl;

cout << "\nPassing an array using the subcript operator:\n";
for(int i=0; i<length; i++)
{
cout << numbers[i] <<", ";
}
}
};

int main()
{
ptrcls obj;
cout <<endl;
}

No comments:

Post a Comment