提问人:Parker 提问时间:3/28/2022 更新时间:3/28/2022 访问量:35
为什么将 char[] 传递给函数而不是 char* 最终会返回奇怪的字符?
Why passing char[] to function instead of char* returns weird chars in the end?
问:
我有以下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 语言中动态分配的字符串
下一个:C - 内存泄漏,函数返回字符*
评论
char str[] = "hello";
sizeof(str)
strlen(str)
\0