为什么将 char[] 传递给函数而不是 char* 最终会返回奇怪的字符?

Why passing char[] to function instead of char* returns weird chars in the end?

提问人:Parker 提问时间:3/28/2022 更新时间:3/28/2022 访问量:35

问:

我有以下C程序:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

void strLower(char *string, char *stringLow);

int main(int argc, char *argv[])
{
    int len = strlen(argv[1]);
    char myString[len];
    strLower(argv[1], myString);


    char *myStringP = (char *)malloc(sizeof(char)*len);
    strLower(argv[1], myStringP);

    printf("String[]: %s\nString *: %s\n", myString, myStringP);
}


void strLower(char *string, char *stringLow)
{
    int len = strlen(string);
    for (int i=0; i<len; i++)
    {
        stringLow[i] = tolower(string[i]);
    }
}

我编译了这个,其中 test.c 是我的文件的名称。之后,我运行我的程序,输出如下:gcc test.c -o test./test helloworld

./test 
String[]: helloworld#=\U
String *: helloworld

我这样做了多次,String[]上的最后一个字符总是不同的。为什么会这样?

阵列 c char malloc

评论

3赞 Christian Gibbons 3/28/2022
看起来您没有为字符串中的终止 null 字符留出空间。
1赞 जलजनक 3/28/2022
检查一下:是 6 而 是 5。最后一个八位字节/字节被 c 字符串分隔符占用char str[] = "hello";sizeof(str)strlen(str)\0

答: 暂无答案