1

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 ?

Vishaal Shankar
  • 1,648
  • 14
  • 26
user3552519
  • 401
  • 4
  • 11
  • 6
    Read a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). For the time being, forget about pointers and use `std::vector` and `std::string` instead – Passer By Mar 07 '18 at 10:58
  • Although there are multiple problems in the code, I ran your code in VS2017 and it did print "abc". So, I'm wondering which null string are you talking about ? – Vishaal Shankar Mar 07 '18 at 11:06
  • 2
    Yes, @PasserBy is correct. Either use C++ with all its modern features or use C. – kometen Mar 07 '18 at 11:08
  • 1
    @VishaalShankar It's called undefined behaviour for a reason – Passer By Mar 07 '18 at 11:08
  • 1
    I think you were told in your previous question that it is almost always wrong to use casts. Well, its wrong this time as well. – john Mar 07 '18 at 11:29

2 Answers2

4

You have (at least) two problems:

  1. The first is that you make p point to the local variable k.
  2. The second is more subtle, and is that you reassign 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).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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.

john
  • 85,011
  • 4
  • 57
  • 81