Linux/C 输入字符串到数组
大家讲道理
大家讲道理 2017-04-17 13:12:31
[Linux讨论组]

有如下代码:

c#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ARGLEN 20

int main()
{
  printf("shot me a string: ");
  char str[ARGLEN];
  fgets(str, ARGLEN, stdin);
  printf("strlen(str) = %d\n", strlen(str));
  str[strlen(str) - 1] = '\0';
  char *cp = malloc(strlen(str) + 1);
  if (cp == NULL) {
    fprintf(stderr, "no memory\n");
    exit(1);
  }
  strcpy(cp, str);

  printf("the final string is: %s\n", cp);
}

运行结果:

bash$ gcc test.c && ./a.out 
shot me a string: helloworld
strlen(str) = 11
the final string is: helloworld
$ gcc test.c && ./a.out 
shot me a string: helloworldhelloworld
strlen(str) = 19
the final string is: helloworldhellowor

输入helloworld返回结果正常, 在内存里str的内容应该是 [h, e, l, l, o, w, o, r, l, d, \n, \0] 所以 strlen(str) = 11, 那么当输入为两个helloworld的时候结果又是什么样的呢?

gdb 调试信息:

bashBreakpoint 1, main () at test.c:13
13    str[strlen(str) - 1] = '\0';
(gdb) p str
$1 = "helloworldhelloworl"
(gdb) p strlen(str)
$2 = 19

说明系统自动把str的最后一个字符替换成了'\0'了?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(1)
巴扎黑

fgets(str, ARGLEN, stdin);
只从stdin里读ARGLEN-1个字符,然后第ARGLEN个位置置为\0。。。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号