Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a local variable from a different function using pointers?

May I have any access to a local variable in a different function? If so, how?

void replaceNumberAndPrint(int array[3]) {     printf("%i\n", array[1]);     printf("%i\n", array[1]); }  int * getArray() {     int myArray[3] = {4, 65, 23};     return myArray; }  int main() {     replaceNumberAndPrint(getArray()); } 

The output of the piece of code above:

65 4202656 

What am I doing wrong? What does the "4202656" mean?

Do I have to copy the whole array in the replaceNumberAndPrint() function to be able to access it more than the first time?

like image 746
Radek Simko Avatar asked Dec 31 '10 13:12

Radek Simko


People also ask

Can I access a local variable in another function?

No you can't, that's what "local" means. Besides that, you don't define a variable of any kind named my_reply anywhere in your code. in the sample code , I have a my function , in my function I am assigning reply to global variable . When I print global variable in my function i.e t .

How do you use a variable from another function in C++?

Put the reference in a global variable. Pass the reference to the other function. Pass the reference to a function that makes it accessible to the other function. Take a pointer as a parameter, and store the reference in the pointed-to location.

Is it possible for a function to access a variable that is local to another function in C?

No. Local variables are stack based: which means that they exist for the lifetime of the function only, and when the function exits the memory they occupied is re-cycled for use by the next function.


1 Answers

myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior.

In practice what happens is that the call to printf overwrites the part of the stack used by myArray and it then contains some other data.

To fix your code you need to either declare the array in a scope that lives long enough (the main function in your example) or allocate it on the heap. If you allocate it on the heap you need to free it either manually, or in C++ using RAII.

One alternative I missed (probably even the best one here, provided the array is not too big) is to wrap your array into a struct and thus make it a value type. Then returning it creates a copy which survives the function return. See tp1's answer for details on this.

like image 159
CodesInChaos Avatar answered Sep 19 '22 07:09

CodesInChaos