|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now! |
|
#1
|
|||
|
|||
|
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. #include <iostream.h> void getName(char*); void main() { char lastName; getName(&lastName); cout << "\nThe name you entered is: " << lastName; } void getName(char*lastName) { cout << "\nPlease enter the last name: "; cin.getline(lastName,25); return; } |
|
#2
|
||||
|
||||
|
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). |
|
#3
|
|||
|
|||
|
Try changing
Code:
char lastName; getName(&lastName); Code:
char lastName [25]; getName(&lastName[0]); |
|
#4
|
|||
|
|||
|
&lastName[0] is equivalent to simply passing lastName. The [0] 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.
|
|
#5
|
|||
|
|||
|
I am aware of that. I just think it makes what is happening a lot clearer to the beginner.
|
|
#6
|
||||
|
||||
|
haahhaa im trying to accomplish the exact opposite of this in my post... LOL
![]() |
|
#7
|
|||
|
|||
|
I never said that I was particularly successful with mine either.
![]() |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > Passing a string by reference |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|