This question already has answers here:
Crash or “segmentation fault” when data is copied/scanned/read to an uninitialized pointer
                                
                                    (5个答案)
                                
                        
                                2年前关闭。
            
                    
因此,我只创建了自己的toupper(大写单个字符)和strupr(大写字符串)。但这是行不通的。所以,这是代码。

#include <stdio.h>

int toupper(const int character) {
    if (character >= 97 && character <= 122)
        return (character - 32);
    return character;
}

char *strupr(const char *string) {
    char *result;
    for (int a = 0; a < strlen(string); a++) {
        *(result + a) = toupper(*(string + a));
    }
    return result;
}

int main() {
    char myString[6] = "Hello";
    printf("myString (Before): \"%s\"\n", myString);
    printf("myString (After): \"%s\"\n", strupr(myString));
    return 0;
}


这是输出:

myString (Before): "Hello"


程序停止后,它只是打印出第一行。所以我需要帮助修复我的代码。

最佳答案

您正在尝试访问未初始化的指针结果。这导致行为不确定:

char * result;
for(int a=0; a<strlen(string); a++)
{
    *result[a] = toupper(string[a]);
}


在访问之前,您需要为该阵列分配足够的内存:

char toupper(const char character)
{
    if(character >= 'a' && character <= 'z')
        return (character + ('A' - 'a'));
    return character;
}

void strupr(const char *string, char *result)
{
    for(int a = 0; a < strlen(string); a++)
        *(result + a) = toupper(*(string + a));
}


int main()
{
    char myString[6] = "Hello", res[6] = {};
    printf("myString (Before): \"%s\"\n", myString);
    strupr(myString, res);
    printf("myString (After): \"%s\"\n", res);
    return 0;
}


或者您可以使用strupr的另一个变体来更改输入字符串本身:

char* strupr2(char *string)
{
    for(int a = 0; a < strlen(string); a++)
        string[a] = toupper(string[a]);
    return string;
}

int main()
{
    char myString[6] = "Hello", res[6] = {};
    printf("myString (Before): \"%s\"\n", myString);
    printf("myString (After): \"%s\"\n", strupr2(myString));
    return 0;
}

关于c - 创建我自己的strupr函数,但是不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53607287/

10-11 22:38