开发者社区> 问答> 正文

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);
}
运行结果:

$ 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 调试信息:

Breakpoint 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'了?

展开
收起
a123456678 2016-06-07 20:49:56 2143 0
1 条回答
写回答
取消 提交回答
  • fgets(str, ARGLEN, stdin);
    只从stdin里读ARGLEN-1个字符,然后第ARGLEN个位置置为0。。。

    2019-07-17 19:31:01
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Debian GNU/Linux 安全合规之路 立即下载
Decian GNU/Linux安全合规之路 立即下载
Linux系统通过fail2ban对暴力破解进行防护 立即下载