首页 > Linux/C 输入字符串到数组

Linux/C 输入字符串到数组

有如下代码:

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


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

【热门文章】
【热门文章】