简体   繁体   中英

Depreciated conversion from string constant to 'char*'

I hope someone can help me. I'm converting a C language program to C++ in order to easily use strings but when I go to compile, I get this error:

inventory.cpp:225: warning: depreciated conversion from string constant to 'char*'

This is where the code in question:

#define FNAME "database.dat"


// test data struct
struct t_Record
{
    int number;
    char word[100];
    //String word[];
} Record;

int main (void)
{
    int Rec = 0; // record number
    FILE *File;

    srand(time(NULL));

    File = FileOpen(FNAME); 
    if (!File)
    {
          printf("Error hommie!\n\n");
          exit(-1);
    }

    ...etc.

This is where the compiler tells me the error occurred:

File = FileOpen(FNAME); 

I just don't see what is wrong...

The place where the compiler tell me to look doesn't even have a string or char associated with it??

Now I understand this error has been seen before, but my question is specific to my code.

The problem is that you are trying to convert a string literal (with type const char[] ) to char* .

The place where the compiler tell me to look doesn't even have a string or char associated with it??

Yes, it is on the top of the file:

#define FNAME "database.dat"

C++ Standard n3337 § 2.14.5/1

String literals

A string literal is a sequence of characters (as defined in 2.14.3) surrounded by double quotes, optionally prefixed by R, u8, u8R, u, uR, U, UR, L, or LR, as in "...", R"(...)", u8"...", u8R"(...)", u"...", uR"* ̃(...)* ̃", U"...", UR"zzz(...)zzz", L"...", or LR"(...)", respectively.

You can avoid the warning by casting to char* :

File = FileOpen( (char*)FNAME);

Even better modify FileOpen to accept a const char* . This will be more safe and just right as you don't intend to modify the string.

As @lizusek said, you can avoid the warning by type casting to char* , but even better would be to rewrite your code to avoid type casting. While it can work and solve a lot of headaches, it can be very dangerous if you type cast the wrong things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM