Reputation: 411
I am trying to print the following using the code as:
int main() {
char p[] = "hello";
char*t = p;
char**b = &t;
std::string s = b[0];
cout<<"string="<<s<<" b[0]="<<b[0];
}
The output I get is as expected:
string=hello b[0]=hello
Now the same thing I want to achieve using a function call in which I pass a variable by reference as:
void func(char**& p) {
char *k = (char*)malloc(8*sizeof(char));
k = (char*)"abc";
p = &k;
}
int main() {
char**j = NULL;
func(j);
std::string s1 = j[0];
cout<<s1;
}
Now I am getting a null string. What could be the reason and how to solve it ?
Upvotes: 1
Views: 456
Reputation: 88027
There is NO WAY to write code like this that follows any sort of standards of good programming. If you are serious about learning how to program you should abandon this mess and rewrite your code to do things the correct way. This is sort of mess is never necessary, even when interfacing with legacy code.
However the following 'works'
void func(char**& p) {
p = new char*;
*p = new char[8];
strcpy(*p, "abc");
}
And take note, I didn't need to use a cast.
Upvotes: 1
Reputation: 409442
You have (at least) two problems:
p
point to the local variable k
.k
losing the original memory you allocated and make k
point to.Then the usual spiel about never using arrays of char
or pointers to char
for strings, when you have std::string
. And that you should never use malloc
in C++, only new
or new[]
. And if you need new[]
consider using std::vector
instead (except for strings of course).
Upvotes: 4