Basic char */const char* problem

I have a problem with some code
MyClass.h
1
2
3
4
5
6
7
8
9
10
11
12
public:
  //stuff

protected:
  // stuff
  char * path;
  //more stuff

   void function1();
   void function2();

};


MyClass.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//stuff

void MyClass::function1() {

      int spinvalue = 50;
      std::cout << "Parameter 1 = " << spinvalue << std::endl;
      std::cout << path << std::endl;
      //stuff
}


void MyClass::function2() 
{
  //stuff

  path = const_cast<char*> ( dialog.get_filename().c_str() );
      std::cout << "pathImagen = " << path << std::endl;

  //stuff
}

// more stuff
}


I need a char * in my function1(). I tried some possibilities, all envolving creating a new class variable (path).

I tried for this variable a char * path, char path[] ... and tried to convert the const char * in that, but for most i got a memory crash and for others i was not obtaining the value in function1().

I don't know what is wrong with it, but when i run function2() and function1() in this order i got :

1 pathImagen = /home/myhome/pathToImage/image.jpg
2 Parameter 1 = 50
3 �6� �

The 1, is the cout just after the const_cast<char*>, the 2 is the spinbutton working and the 3 is some random garbage :S

Anyone know what i'm doing wrong or know the way to do what i want? any lead/hint/help will be appreciated.

Thx in advance for all!
Last edited on
¿what is dialog, and what is its scope? You are just pointing at that place, so if it is destroyed between your calls, it is garbage.

¿are you sure that you want a char* ? ¿what for?
Edited
Last edited on
I answer it myself

The problem was that the memory that the pointer was pointing is free when the function ends, so i use a std::string as the variable in the header and then use path = std::string(dialog.get_filename().c_str()) and path.c_str() to access where i want
Solved

Thx to all the leads and hints!
path = dialog.get_filename(); I think that should work.
Topic archived. No new replies allowed.