I wanted to changed a variable with passing the method. I used traditional C way. I wrote this code in Visual Studio 2010 with Visual C++. However it does not give expected result.
Code have been a purpose but I changed it for easy understandability.
#include<cstdio>
using namespace std;
void exampleMethod(char *array) {
array = new char[6];
array[0] = 'h';
array[1] = 'e';
array[2] = 'l';
array[3] = 'l';
array[4] = 'o';
array[5] = 0; // for terminating
fprintf(stdout, "exampleMethod(): myArray is:%s.\n", array);
}
void main() {
char* myArray = 0;
exampleMethod(myArray);
fprintf(stdout,"main(): myArray is:%s.\n", myArray);
getchar(); // to hold the console.
}
Output of this code is:
exampleMethod(): myArray is:hello.
main(): myArray is:(null).
I don't understand why pointer value was not changed in main()
. I know that it is pass by reference and I changed myArray's values with pointer. I also used new-operator to initialize that pointer.
After that, I changed code, I initialized variable myArray
in main method with new-operator. (before it is in exampleMethod()
.)
void exampleMethod(char *array) {
array[0] = 'h';
array[1] = 'e';
array[2] = 'l';
array[3] = 'l';
array[4] = 'o';
array[5] = 0; // for terminating
fprintf(stdout, "exampleMethod(): myArray is:%s.\n", array);
}
void main() {
char* myArray = new char[6];;
exampleMethod(myArray);
fprintf(stdout,"main(): myArray is:%s.\n", myArray);
}
Surprisingly, code is running properly. It gives this ouput:
exampleMethod(): myArray is:hello.
main(): myArray is:hello.
Why did not previous code run in such a way that I expected? I compiled and run it with Visual Studio 2010 that is Visual C++ project. I also tried it with Visual Studio 2015.
You're passing a copy of the pointer by void exampleMethod(char *array)
, so any change to the pointer in exampleMethod()
will not affect the pointer in main()
.
You may want to pass it by reference (add an ampersand &
before the identifier to make it a reference):
void exampleMethod(char * &array)
So in this way any modification to the pointer in exampleMethod
will apply to the pointer in main()
, too, as they are the same object now.
And a side note: Don't forget to delete[]
the array whenever you get it from dynamic allocation.