cstr

Hi all,

I'm new to C++ and working my way through an SDL tutorial. One thing that wasn't explained well relates to the following function, which is used to load images:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
SDL_Surface *load_image( std::string filename )
{
    //image loaded
    SDL_Surface* loadedImage = NULL;

    //optimised image
    SDL_Surface* optimisedImage = Null;

    //load image
    loadedImage = IMG_Load( filename.c_str() );

    //if image loaded
    if( loadedImage != NULL )
    {
        //create optimised
        optimisedImage = SDL_DisplayFormat( loadedImage );
        //free old image
        SDL_FreeSurface( loadedImage );
    }

    return optimisedImage;
}


The argument of IMG_Load is what I'm having trouble with. I can see from the documentation that it accepts char* as argument, which isn't the same thing as string (although I'm not completely clear on what the difference is).

So I assume the function c_str converts string to char*, is that correct? In any case, why is the format filename.c_str() and not c_str(filename) ? I thought that the x.y() syntax was reserved for calling functions from classes?

Basically if someone can explain the syntax and the difference between the different string representations that would be great.

Cheers!
Last edited on
Look at the string class reference here on cplusplus.com.

std::string(filename is an std::string) IS a class and cstr() is a member function that converts it to a C string(char*).
Last edited on
Oh right, I think I get it now, thanks. The reference modules on here seem really useful, but they're a bit over my head at the moment still. Sometimes it's easier to have someone explain it to you to get you going.

So, here, filename is an instance of a string, and c_str() is a member function which acts on a string instance to give the char* "C string" equivalent of that instance? Is the returned C string also an instance of a class? The terminology is still pretty new to me.

In that case, wouldn't it have been better for me to have set up the filename as a C string in the first place, so I wouldn't even need to use the header <string>, and I can perform fewer operations? Is there any reason to use string instead?
Last edited on
strings are more complicated than they seem.

The string class takes care of things like memory management, and makes it effortless to modify/append things to the string.

Using char arrays is an option, but is more complicated because more of the responsibiliy falls on your shoulders, rather than having the string class takes care of things for you.
Topic archived. No new replies allowed.