Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ char * pointer passing to a function and deleting

Tags:

c++

pointers

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?

like image 256
Narek Avatar asked Nov 28 '22 11:11

Narek


1 Answers

As GregS has said, the simplistic answer is to declare your function using a reference:

void func(char *&aString)

However it is not really the best solution. In C++ you generally avoid simple arrays and use containers.

#include <iostream>
#include <string>

void func(std::string &s)
{
    std::getline(std::cin, s);
}

int main()
{
    std::string str;
    func(str);
    std::cout << str << std::endl;
    return 0;
}
like image 182
Michael J Avatar answered Dec 10 '22 05:12

Michael J