I have a the following code:
#include <iostream>
using namespace std;
void func(char * aString)
{
char * tmpStr= new char[100];
cin.getline(tmpStr,100);
delete [] aString;
aString = tmpStr;
}
int main()
{
char * str= new char[100];
cin.getline(str,100);
cout<< str <<endl;
func(str);
cout<< str <<endl;
return 0;
}
Why the second cout does not print the second input string? How can I change this code to work it?
Because the second
coutwill print what is pointed bystr. Andstr, the pointer, in your main function will have the same value before and after the call tofunc.Indeed, in the
funcfunction, you are changing the value of theaStringvariable. But this is another variable thanstrin main.If you want the value of
strto be changed, you have to pass it tofuncby reference or by pointer. (Note that what you write, is to pass the characters by pointer. I mean you have to pass the pointer by pointer:void func(char **str_ptr), or by referencevoid func(char *&str_ref))If you’re really doing C++, you should use std::string instead of the old C strings.
An example of passing the pointer by pointer:
Plus you should call it like this:
func(&str);