How to convert a string to const char *?

Asked

Viewed 5,189 times

7

I’m trying to make an audio player (an mp3 player) using the library SDL_mixer.

The problem is that I have a function that returns a string (a music directory) that I need to pass this string as an argument to the function *Mix_LoadMUS(const char *file).

I am beginner in programming (1st period), I will be grateful if the answers are simplified.

How do I turn a string into a type const char*?

  • 3

    Is this string the string type of C++, or is it a string type of another library? If it is the default C++ type, I think s.c_str() returns a standard C-compatible const char * .

  • 1

    The "const char *file" specification is only to ensure that the function will not modify the content pointed by the file pointer.

  • I am using only C, this string comes from a function written with the GTK library, this function is a (File_chooser) screen where the user chooses the file he wants to open. I can view the contents of the string by printing it into a file (fprintf). The problem is that when I try to pass this string to the other function, the program closes.

  • It’s kind of like Gstring?

  • 2

    Put the code snippet please.

3 answers

2

If it’s GTK+ Gstring, use

astringemquestao->str

that points directly to the buffer containing the string. It is terminated null and can be used where a const char * is expected.

Remember that: any modification in Gstring, the value of the str member can change. Therefore this pointer should not be reused. If you need to have access to the string during a longer time interval, during which Gstring may change, make a copy and use the copy, not forgetting to release it later.

1

If you are using a Std string (Std::string), call the c_str function().

For example:

std::string str;

...

Mix_LoadMUS(str.c_str());
  • was quoted in the comments that is used only C.

0

The qualifier const only indicates that the variable cannot be changed.
So the code below means that the data pointed by the file pointer is not changeable:

void Processa(const char * file)
{
      ....
}

The compiler is in charge of generating an error alert if the code in the routine tries to change the content pointed by the pointer. Note that const char *p or char const *p has the same meaning, that is, the pointed data are not modifiable. But char * const p means the pointer is constant and cannot be modified.
So it should be no problem, you pass a string variable without const qualifier to a routine like the one shown in your question.

[EDIT]
Rereading your question I realized that your problem is that the parameter you are trying to pass to the routine is generating the error when compiling, correct? If yes, test use casting to tailor the parameter to what is required by the call routine, for example:

   char *p = Mix_LoadMUS ( (const char *) file )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.