使用函数[复制]在C中使单词小写

问题描述 投票:-4回答:1

我不确定问题是什么。该函数似乎运行良好,但在主函数中,当使用printf进行测试时,它不会显示结果。

char* MotMiniscule(char* mot)
{
char motm[100],c,*motf;
int i=0;
strcpy(motm,mot);
c=motm[i];
while(c!='\0')
{
    printf("%c \n",c);
    motm[i]=tolower(c);
    i++;
    c=motm[i];
}
strcpy(motf,motm);
printf("%s\n",motf);
return(motf);
}

main()
{
char *mot="HEllooOoMA",*min;
min=MotMiniscule(mot);
printf("\n le mot est %s:\n",mot);
printf("|| %s  ||",min);
}

c arrays char
1个回答
2
投票

你从未在函数motf中为指针MotMiniscule分配空间:

strcpy(motf,motm);

这是未定义的行为,因为motf中的地址是不确定的。你应该给它一些空间来指出:

motf = malloc(100);

完整的代码应该是:

char* MotMiniscule(char* mot)
{
    char motm[100],c,*motf;
    int i=0;
    strcpy(motm,mot);
    c=motm[i];
    while(c!='\0')
    {
        printf("%c \n",c);
        motm[i]=tolower(c);
        i++;
        c=motm[i];
    }
    motf = malloc(100); // Allocate some memory
    strcpy(motf,motm);
    printf("%s\n",motf);
    return(motf);
}

int main()
{
    char *mot="HEllooOoMA",*min;
    min=MotMiniscule(mot);
    printf("\n le mot est %s:\n",mot);
    printf("|| %s  ||",min);
    free(min); // Don't forget to free dynamically allocated memory
}

正如John Bode所指出的那样,使用motm是完全多余的。你可以安全地删除它。此外,动态分配的大小应该依赖于mod的长度。所以这个代码的精炼版本就是这样。

char* MotMiniscule(char* mot)
{
    char c, *motf;
    int i = 0;
    c = mot[0];
    motf = malloc(strlen(mot) + 1); // Allocate some memory
    while (c != '\0')
    {
        printf("%c\n", c);
        motf[i] = tolower(c);
        i++;
        c = mot[i];
    }
    // No need to copy again, but
    motf[i] = '\0'; // Remember to terminate it
    printf("%s\n", motf);
    return(motf);
}

int main()
{
    char *mot = "HEllooOoMA", *min;
    min = MotMiniscule(mot);
    printf("\n le mot est %s:\n", mot);
    printf("|| %s  ||", min);
    free(min); // Remember to free it
}
© www.soinside.com 2019 - 2024. All rights reserved.