我正在尝试编写一个可以为用户输入调用的函数,因此我可以随时调用它并且可以将它分配给一个变量。
但是,出于某种原因,它似乎将输入限制为 8 个字符,无论它是高于还是低于 8 个字符。
char * userInput(){
char * user_input;
user_input = malloc(sizeof(char)*100);
printf("Type > ");
scanf("%s",user_input);
printf("%ld",sizeof(user_input));
return user_input;
}
输出
类型 > TheIsTheSentence
8你好TheIsThe
有问题的语句是这样的
printf("%ld",sizeof(user_input)); /* It desn't return the number of char stored in user_input */
因为 user_input
是字符指针,sizeof 指针在 32
位机和 8 上总是 4
字节
在 64 位机器上的字节数。
我的建议是使用 fgets()
而不是 scanf()
。例如
声明一个字符指针并分配内存。
char * user_input = NULL;
user_input = malloc(sizeof(*user_input) * MAX_BUF_SIZE); /* Instead of magic number use macro */
对 malloc()
进行正确的错误处理。例如
if(user_input == NULL) {
fprintf(stderr, "memory allocation failed\n");
exit(-1);
}
使用 fgets()
而不是 scanf()
扫描输入。例如
size_t retStrCspn = 0;
if(fgets(user_input, MAX_BUF_SIZE, stdin) != NULL) {
/* fgets success. next task is remove the trailing \n char read by fgets() */
user_input[retStrCspn = strcspn(user_input, "\n")] = 0; /* remove the trailing & use the return value */
}
现在打印长度,不要使用sizeof
,例如使用strcspn()
的返回值
printf("%zu", retStrCspn);