#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
char str[5]={'\0'};
printf("Initial length before passing = %ld\n",strlen(str));
input(str);
printf("Received string = %s\n",str);
printf("Length after getting input(calling function) = %ld\n",sizeof(str));
}
input(char * buffer)
{
puts("Enter something: ");
printf("Initial length after passing = %ld\n",strlen(buffer));
if ( fgets(buffer, sizeof(buffer), stdin) == NULL )
return -1;
else
{
printf("Length after getting input(called function)= %ld\n",strlen(buffer));
return 0;
}
}
输出 1
Initial length before passing = 0
Enter something:
Initial length after passing = 0
hello
Length after getting input(called function)= 6
Received string = hello
Length after getting input(calling function) = 5
输出 2
Initial length before passing = 0
Enter something:
Initial length after passing = 0
helloooooo
Length after getting input(called function)= 7
Received string = hellooo
Length after getting input(calling function) = 5
为什么当我给出不同的输入时它会打印不同的长度?
- 在输出 1 和 2 中,当我只为 5 个字符分配空间时,为什么初始长度为 6?
- 为什么传入输出 1 和输出 2 之前和之后的字符串长度不同?
- 在输出 2 中,当我只分配较少的空间时,为什么“获得输入后的长度(称为函数)= 7”?