Modifying a c string [duplicate]

对着背影说爱祢 提交于 2019-12-20 06:17:49

问题


I'm trying to implement tolower(char *) function, but I get access violation error. I came to know that this is because to compiler stores string literals in a read-only memory. Is this true? Here's some code:

char* strToLower(char *str)
{
    if(str == nullptr)
        return nullptr;

    size_t len = strlen(str);
    if(len <= 0)
        return nullptr;

    for(size_t i = 0; i < len; i++)
        *(str+i) = (char)tolower(*(str+i));//access violation error

    return str;
}

int main()
{
    char *str = "ThIs Is A StRiNgGGG";

    cout << strToLower(str) << endl;

    system("pause");
    return 0;
}

If this is true, how am I supposed to implement such function?


回答1:


Yes, it's true. You cannot modify a string literal. In fact, if your compiler were not from 1922 it would have prevented you from even obtaining a non-const pointer to a string literal in the first place.

You didn't state your goals, so when you ask "how am I supposed to implement such function" it's not really clear what you want to do. But you can make a copy of the string literal to get your own string, then modify that as you please:

// Initialises an array that belongs to you, by copying from a string literal
char str[] = "ThIs Is A StRiNgGGG";

// Obtains a pointer to a string literal; you may not modify the data it points to
const char* str = "ThIs Is A StRiNgGGG";

// Ancient syntax; not even legal any more, because it leads to bugs like yours
char* str = "ThIs Is A StRiNgGGG";

Of course, since this is C++, you should not be using C-strings in the first place:

std::string str("ThIs Is A StRiNgGGG");


来源:https://stackoverflow.com/questions/29195887/modifying-a-c-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!