在经历了多个在C中按值传递字符串的例子后,我仍然不明白为什么下面的代码不能在中工作
int main(void){
char *fileList;
strcpy(fileList,"This is a test linen");
char type = 'F';
if(checkFileList(fileList, type)){
printf("Proper File listn");
}
else{
printf("Improper File listn");
}
}
int checkFileList(char *string, char type){
// Do something with string
}
如果我将主函数中的变量fileList定义为-,这个程序就会工作
char fileList[128];
但我不能为这个字符串提供固定的大小,因为我只在运行时得到这个字符串,因此不知道它会有多长
我在这里做错了什么?请注意,我不想通过引用传递字符串,因为我将在函数中更改字符串,并且不希望这反映在原始字符串中。
在您的代码中
char *fileList;
strcpy(fileList,"This is a test linen");
调用未定义的行为,作为,fileList
在未初始化的情况下使用。
在使用fileList
之前,您需要将内存分配给它。也许malloc()
和函数家族会帮助您做到这一点。另外,请阅读free()
。
FWIW,
如果我将主函数中的变量fileList定义为-
,则此程序有效char fileList[128];
因为fileList
在这里是一个数组,并且内存分配已经由编译器完成。所以,使用它是可以的。
BTW"按值传递字符串"是对术语的滥用。C对任何函数参数的传递都使用pass-by-value。
为了在运行时为字符串分配内存,您最好先知道字符串的大小:
int main(void){
const char *str = "This is a test linen";
int len = strlen(str);
char *fileList = malloc(len);
// then later you also have to take care for releasing the allocated memory:
free(fileList);
}