Hi, recently i doing some work about converting Fortran to C++
Fortran have a function call SUBROUTINE, which can return multiple values include array in the function.
But I can't find any thing that can passing this 2 data type in C++
#include <iostream>
#include <fstream>
#include <math.h>
#include <stdio.h>
usingnamespace std;
// Declare function TRY and accessing the array
void TRY ()
{
int D[6]={1,2,3,4,5,6};
int A;
A=1;
}
int main ()
{
int A;
int D[6];
TRY(); //Calling function TRY
cout<<A<<"\n";
cout<<D[4];
std::system ("PAUSE");
}
from the code, i need accessing and storing array in other function, i just need the function TRY help me do something then the main function just call the answers from function TRY when need it.
who can help me? thanks...
In your above code, you have declared an integer array and an integer in your function as well as main. But these variables have a scope of only the block they are defined in.. so it won't work the way you want it to... If you want your function to access a variable from the main, pass the address of the variable to the function...
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
void TRY (int *p, int*q) //p and q are pointers. They accept address of passed arguments
{
*p=1; //Assigns 1 to the value at address pointed by p
q[4]=5; //Assigns value 5 to the fourth element in the array pointed by q.
}
void main ()
{
int A;
int D[6];
TRY(&A, D); //Passes the address of variable A and array D to the function..
//The address of an array is the name of the array itself, so no & sign...
cout<<A<<"\n";
cout<<D[4];
getch();
}
Yeah, I know.. I'm using a damn old version of TurboC++... VisualC++ is a lil complicatd to undrstnd.. Anyways, I've shifted to VC++ 10.0, just fr quick compiling i use TC...
There are many simpler, modern compiler-IDE-bundle options; some of them are juts as fast and easy as TC++, and they have the added advantage of being up to date.
Why does your subfunction return A ? You don't use the returned value, and you don't even need one, since you're passing by reference (not that it makes any sense to - your subfunction doesn't use it).
Also, this: int(&D)[6] is just ugly and far more effort than needed, and inflexible. How about this instead:
Of course, given that the pointer doesn't actually change throughout the function, there's no reason to return it. The calling code has access to the exact same pointer and can just carry on using it, so even better would be:
If the function you are designing needs to take an array of three ints and will only ever take an array of three ints it would be safer to make it take a reference to an array of three ints?
I would say that it is unwise to give blanket advice based on weather the code is ugly or to specific, but that's just me.