【问题标题】:toLower string in C 0xC0000005toLower C 中的字符串 0xC0000005
【发布时间】:2020-11-25 06:16:34
【问题描述】:

好吧,我有这段代码,我正在尝试开始工作,但无论我继续得到什么,我都会得到 0xC0000005

int main()
{
    if(stringContains("hello", "Hello world", FLAG_CASE_SENSITIVE))
    {
        printf("Works");
    }
    
    printf("%i", stringContains("hello", "Hello world", FLAG_CASE_SENSITIVE));
    return 0;
}

#define FLAG_CASE_INSENSITIVE 0
#define FLAG_CASE_SENSITIVE 1
    
typedef enum { false, true } bool;
    
bool stringContains(char* needle, char* stack, int type);
char* toLower(char* s);
    
bool stringContains(char* needle, char* stack, int type)
{
    if(type == FLAG_CASE_SENSITIVE)
    {
        return (strstr(toLower(stack), toLower(needle)) != 0) ? true : false;
    }
    return (strstr(stack, needle) != 0) ? true : false;
}

char* toLower(char* s) {
    for(char *p=s; *p; p++) *p=tolower(*p);
    return s;
}

我必须承认,我在 C 方面非常基础

【问题讨论】:

  • 您将 字符串文字 传递给试图修改它们的函数。字符串文字是只读的。
  • OT:您需要在调用函数之前声明它们。也就是说,将前向声明移动到文件的顶部。
  • @kaylum 我做了,只是我合并了几个文件,这就是为什么它看起来像这样。
  • @EugeneSh。嗯,好吧,我该怎么办?我对此真的很陌生:(
  • 要么不将字符串文字传递给这些函数,要么修改函数以使其不尝试修改字符串。就个人而言,我更喜欢后一种方法。

标签: c


【解决方案1】:

Try to declare functions which will accept literals as const`:

bool stringContains(const char *needle, const char *stack, int type);

然后当你调用另一个函数时,如果const 被剥离,你会收到警告。

https://godbolt.org/z/x4z5vE

你需要摆脱这个问题。 Cast 无济于事,因为它只会使警告静音,但不会更改有关字符串的任何内容,因此您需要创建字符串的可写副本。

bool stringContains(const char* needle, const char* stack, int type)
{
    
    if(type == FLAG_CASE_SENSITIVE)
    {
        char *haystack = strdup(stack);
        char *newneedle = strdup(needle);
        char *result = NULL;
        if(haystack && newneedle)
            result = strstr(toLower(haystack), toLower(newneedle));
        free(newneedle);
        free(haystack);
        return !!result;
    }
    return !!strstr(stack, needle);
}

https://godbolt.org/z/Kvdxq3

【讨论】:

    猜你喜欢
    • 2011-03-25
    • 2015-06-21
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    相关资源
    最近更新 更多