April 15th, 2003, 12:34 PM
Passing a string by reference
I am trying to pass the string lastName by reference from the called function getName to the calling function main. I am tring to set up an array of 25 characters for the user to enter their last name. I want the user to enter their name in the getName function and then pass it through to the main function and display it from there with out using any global variables. When I run this program it always shuts down my compiler.
Here is the program. Please help me if you can.
cout << "\nThe name you entered is: " << lastName;
cout << "\nPlease enter the last name: ";
April 15th, 2003, 02:52 PM
Your program is crashing because for whatever you input, you start overwriting the data that follows your variable, most likely return addresses and the like. The effect is called "clobbering your data". The technique by which you are achieving that effect is called "buffer overflow", ie writing past the end of your buffer.
In this case, your buffer has a length of one. It needs to be larger, large enough to contain the longest allowable input string plus one more for the null terminator that marks the end of the string. lastName needs to be declared as a character array; remember to declare it as at least one character larger than you need.
And since an array name is the same thing as a pointer, you do not need to use the address operator (&) when you call getName. The compiler will complain about it anyway (different levels of indirection or something similar).
April 15th, 2003, 02:57 PM
char lastName ;
April 15th, 2003, 05:02 PM
&lastName is equivalent to simply passing lastName. The  de-references the lastName pointer at index zero, then the & operator takes the address of it. This is the same thing as passing the raw lastName pointer by itself.
April 15th, 2003, 05:32 PM
I am aware of that. I just think it makes what is happening a lot clearer to the beginner.
April 15th, 2003, 05:47 PM
haahhaa im trying to accomplish the exact opposite of this in my post... LOL :D
April 16th, 2003, 08:28 AM
I never said that I was particularly successful with mine either. :)