gpt4 book ai didi

c - c 中的 fgets 和 strlen

转载 作者:太空宇宙 更新时间:2023-11-04 06:33:53 24 4
gpt4 key购买 nike

#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. 在输出 1 和 2 中,当我只为 5 个字符分配空间时,为什么初始长度为 6?
  2. 为什么输出1和输出2传入前后字符串长度不一样?
  3. 在输出 2 中,当我只分配了更少的空间时,为什么“获取输入后的长度(调用函数)= 7”?

最佳答案

strlen 应该使用 C 字符串,即以 \0 结尾的字符数组。当你定义:

char str[5];

str 包含垃圾,您很幸运调用 strlen 没有导致段错误。

关于c - c 中的 fgets 和 strlen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17257107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com