1
#include <iostream>
#include<string.h>
using namespace std;
char *rt()
{
    char a[20];
    strcpy(a,"I am a beginner");
    cout<<a;
    return a;
}
int main()
{
    char *a;
    a=rt();
    cout<<endl;
    cout<<a;
    return 0;
}

Here I have made a short program for understanding the same....I was expecting the output to be as

I am a beginner 
I am a beginner

UPDATE: But it turned out to be

I am a beginner
ëóG

I have read many articles and post but I am not able to understand their complex language....so I will appreciate a no-nonsense answer ( for a stupid...like me!!)

UPDATE: Actually, there is one question in my assignment which goes like this

class COMPUTER
{
    char chiptype[10];
    int speed;
public:
    void showdetails()
    {
        cout<<chiptype;
        cout<<"\t"<<speed;
    }
    void getdetails()
    {
        cin.getline(chiptype,10);
        cin>>speed;
    }
};

Here the data has to be read and stored into a binary file....and the records having chiptype as "CD" are to be displayed.

Now my question is that...as the variable chiptype is private so I can't use it for comparison in main()....so I thought of making a function which returned the value stored in chiptype.

And I am not allowed to use std::string as well as node implementation...

Alu
  • 38
  • 1
  • 5

4 Answers4

3

char a[20]; is allocated on stack. When the function rt() returns, the stack unwinds and a goes out of scope. Hence you do not get your desired result.

While you are on C++, may I suggest using std::string

Read the comment below:

The other trick is to wrap the array in a struct, and return the struct. Since a struct is copyable, the array internally becomes copyable and will not lose scope. See this answer. Then you're not dealing with pointers at all. See this live example – PaulMcKenzie

Alu
  • 38
  • 1
  • 5
Rishi
  • 1,387
  • 10
  • 14
  • is std::string the only way – Alu Feb 11 '17 at 18:48
  • @Mukund Create your own `string` class. Otherwise what you're learning is `C`, not C++. – PaulMcKenzie Feb 11 '17 at 18:49
  • You could pass a char array to fill as parameter, isntead of returing it. Or allocate something with new[] in the function (ugly because you need to delete[] it outside). And yes, this is perfectly valid C++, even if some people don't like it. – deviantfan Feb 11 '17 at 18:50
  • you can allocate string in function and return pointer. e.g. char* str = new char[20]; The caller would have to free the string using delete[]. however, std::string is so much easier – Jimmy Feb 11 '17 at 18:52
  • The other trick is to wrap the array in a struct, and return the struct. Since a `struct` is copyable, the array internally becomes copyable and will not lose scope. See [this answer](http://stackoverflow.com/questions/27410943/returning-arrays-from-a-function-in-c/27411483#27411483). Then you're not dealing with pointers at all. [See this live example](http://ideone.com/o1eqtS) – PaulMcKenzie Feb 11 '17 at 18:56
  • @Mukund, you can allocate the char array on a heap using `new`. That way main will also have access to it. But then you have to take care of deleting the allocated memory. – Rishi Feb 11 '17 at 19:10
  • **char a[20]; is allocated on stack** do u mean that the character array **a** is implemented through stack ? – Alu Feb 11 '17 at 19:43
  • @Mukund, do not confuse it with the data structure ``. Read [this](http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap) – Rishi Feb 11 '17 at 19:46
  • @Mukund Did you see my example? You can have an array internally inside a struct, and return the struct. The only difference is that you have to prepend the struct instance name before the array name using the `.`. syntax. That is the simplest, cleanest, way to "return a string" without using `new` and without using `std::string`. – PaulMcKenzie Feb 12 '17 at 00:00
2

Use std::string instead of char[]

#include <iostream>
#include<string>

std::string rt()
{
    std::string a("I am a beginner");
    std::cout<<a;
    return a;
}
int main()
{
    std::string a;
    a=rt();
    std::cout<<std::endl;
    std::cout<<a;
    return 0;
}

In your original code char a[20] is allocated on the stack and return a; will return a pointer to a stack variable that is no longer valid when you receive it in you main() -- handling strings in c++ should generally be done using std::string as it handles all the nasty memory management that wil kill your program if you aren't careful.

If you have to use pointers and not use std::string, you would need to go the c style way with the risk of having memory leaks if you miss a step or two. The code would look something like this using c style (keeping the cout c++)

#include <iostream>
#include <strings.h>

std::string rt()
{
    char *a = malloc(20); // allocate the memory on heap
    strcpy(a,"I am a beginner");
    std::cout<<a;
    return a;
}
int main()
{
    char *a;
    a=rt();
    std::cout<<std::endl;
    std::cout<<a;
    free(a); // release the memory
    return 0;
}

Caution: I don't recommend that you do the above style -- in a real world application you will likely get into trouble by either forgetting to free the memory, or accidentally accessing the memory after it has been free'd

Soren
  • 14,402
  • 4
  • 41
  • 67
  • 2
    @Mukund Then your syllabus is sorely lacking. The `std::string` has been part of C++ for 19 years now. – PaulMcKenzie Feb 11 '17 at 18:48
  • @Mukund -- it is what you should be doing regardless -- otherwise you will have to go `c` style instead of `c++` and start malloc and free to do you own memory management. – Soren Feb 11 '17 at 18:48
  • Programming C++ does not always mean you have access to the STL. E.g. the AVR toolchain supports C++ , but no STL – koalo Feb 11 '17 at 18:55
  • @koalo -- that may be so, but a sensible programmer would then create a std::string-lite classes for what he needs -- answeing that would be out-of-scope for a beginner's-question (such as the case with the OP) – Soren Feb 11 '17 at 19:01
  • @Soren: Yes, I agree! – koalo Feb 11 '17 at 19:02
1

The problem is that the memory of a will be destroyed as soon as program returns from the function. I do not think you should work with dynamic memory at your level of knowledge, so I suggest you define the array outside and just modify it inside the function:

#include <iostream>
#include<string.h>
#define MAX_LENGTH 20
using namespace std;

void rt(char *a)
{
    strcpy(a,"I am a beginner");
    cout<<a;
}

int main()
{
    char a[MAX_LENGTH];
    rt(a);
    cout<<endl;
    cout<<a;
    return 0;
}

Furthermore, you should take care that rt is not writing more than MAX_LENGTH characters.

koalo
  • 2,113
  • 20
  • 31
0

As mentioned by other use std::string instead of char [].

std::string rt()
{
    std:: string a = "I am a beginner"; // This statement is equivalent to         std::string a("I am a beginner");
    std::cout << a "\n";
    return a;
}

Main reason of not getting the desired result is " char a[] is allocated on stack, but when function return stack become empty.

P.S : You need to include <string> in your program, to use std::string

Shravan40
  • 8,922
  • 6
  • 28
  • 48