hi everybody i am new to progamming my question is how can i make this sample with using a pointer
#include <iostream>
#include<conio.h>
using namespace std;
#include <iostream>
#include<conio.h>
using namespace std;
double &f(int i); // return a reference
double vals[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
int main()
{
int i;
cout << "Here are the original values: ";
for(i=0; i < 5; i++)
cout << vals[i] << ' ';
f(1) = 8.23; // change 2nd element
f(3) = -8.8; // change 4th element
cout << "\nHere are the changed values: \n";
for(i=0; i < 5; i++)
cout << vals[i] << ' ';
return 0;
}
double &f(int i)
{
return vals[i]; // return a reference to the ith element
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include <iostream>
#include<conio.h>
using namespace std;
#include <iostream>
#include<conio.h>
using namespace std;
double &f(int i); // return a reference
double vals[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
int main()
{
int i;
int *ptr = &i;
cout << "Here are the original values: ";
for(i=0; i < 5; i++)
cout << vals[i] << ' ';
//random pointer stuff
*ptr = 12; //Might break something, I don't know.
f(1) = 8.23; // change 2nd element
f(3) = -8.8; // change 4th element
cout << "\nHere are the changed values: \n";
for(i=0; i < 5; i++)
cout << vals[i] << ' ';
return 0;
}
double &f(int i)
{
return vals[i]; // return a reference to the ith element
}
|
This what you looking for?
Be generic, you get what you get
Last edited on
hi again i am trying this way but i get erros
#include <iostream>
#include<conio.h>
using namespace std;
#include <iostream>
#include<conio.h>
using namespace std;
double *f(int i); // return a reference
double vals[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
int main()
{
int i;
cout << "Here are the original values: ";
for(i=0; i < 5; i++)
cout << vals[i] << ' ';
f(1) = 8.23; // change 2nd element
f(3) = -8.8; // change 4th element
cout << "\nHere are the changed values: \n";
for(i=0; i < 5; i++)
cout << vals[i] << ' ';
return 0;
}
double *f(int i)
{
return &vals[i]; // return a reference to the ith element
}
You should change these statements
f(1) = 8.23; // change 2nd element
f(3) = -8.8; // change 4th element
to
*f(1) = 8.23; // change 2nd element
*f(3) = -8.8; // change 4th element