Question:
C++ How to access variable in memory after the function has ended?
???
2011-01-30 01:56:58 UTC
Hi, I'm having trouble with this homework problem. I want to write a void function with a parameter that takes a variable, for example: void test (int x). This function adds two numbers and prints the result. Let's say I call this function twice in a row, with values 1 and 2 for x. How can I access the previous value of x and add it to the current value of x the second time around? Without creating a global variable?

I would like:
test (1) to output 1
test (2) to output 3

Am I supposed to create a memory leak on purpose? Even if this is the case, I'm still stuck.

Thanks for any help.
Four answers:
Techwing
2011-01-30 03:03:57 UTC
You need simultaneous access to both variables in order to compute their sum, unless the function is guaranteed to be called only twice during the entire execution lifetime of the program. In the latter case, the following code will work. Note that the static variable in the SumIt() function is not a global variable; it has only function scope and cannot be referenced outside the function. Pointers are presumably not an option, since you indicate that the single argument of the function must be int.



#include

using namespace std;



void SumIt(int);



int main(int iArgs, char *pszArgs[])

{

int x=3, y=7;

SumIt(3);

SumIt(7);

return 0;

}



void SumIt(int x)

{

static int sum=0;

sum+=x;

cout << sum << endl;

return;

}



Your instructor has imposed a number of truly brain-dead restrictions, and has inadequately defined the problem to be solved as well. You may take consolation in the fact that nobody in the real world codes this way, outside the ivory towers of academia.
sporkatron
2011-01-30 10:32:56 UTC
Pass into the function a pointer to a variable declared in your main/ calling function. You can then use the pointer name to assign the value to the original variable.
Rinku
2011-01-30 10:10:11 UTC
test can be written as following

int test(int x)

{

static int sum = 0;



if(sum == 0)

{

sum = x;

}

else

{

x += sum;

sum = 0;

}



return x;

}



This will give sum of two consecutive call without 0 as parameter.

Also you have to protect the static variable/call if the program is multi-threaded.



PS: why you are passing only one parameter when you know you have 2 number to add. Pass both number and return the sum. :)

ra
2011-01-30 09:58:42 UTC
Needs a global, by definition.



Or the calling procedure needs to have the new value returned to it by the function, to be passed to it next time it is invoked.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...