Hi,

I have written the following program but its not doing what's it supposed to do ! For some reason sometimes nothing or rubbish is being printed onto the screen. However, if I don't use function but instead do everything within main(), then its fine. What's the problem with the prgram ?

#include <iostream>
#include <string>

using namespace std;

const char* getArray(string s){
    const char* temp = s.c_str();
    return temp;
}

int main(){
    string s = "STRANGE";
    const char* temp = getArray(s);
   
    int i = 0;
    while(temp[i] != '\0'){
        cout<<temp[i]<<" ";
        i++;
    }
    cout<<endl;   

    return 0;
}

Thanks

you need to pass the string by reference. in GetArray() the string is local to the function so when the function returns the string is destroyed, invalidating the return pointer. const char* getArray(string& s){ Actually the function doesn't need the temp pointer at all.

const char* getArray(string& s)
{
    return s.c_str();
}

This page describes exactly the problem you're having ...

To the OP: I would like to notice you that your function getArray() is returning a constant value which means the value it returns isn't changeable ...

If you want your function returning editable values you should change it to something like this:

char* getArray(const string & s)
{
	char * modif = new char[strlen(s.c_str())+1];
        strcpy(modif, s.c_str());
	return modif;
}

NOTE: If you're using this function please don't forget to delete the assigned memory ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.