【问题标题】:Copy two parts of a string to two other strings using strncpy使用 strncpy 将字符串的两个部分复制到其他两个字符串
【发布时间】:2020-04-21 20:55:14
【问题描述】:

我想将字符串s的两部分复制到两个字符串a和b:

#include <stdio.h>
#include <string.h>
int main()
{
   char s[] = "0123456789ABCDEF";
   char a[10];
   char b[6];
   strncpy( a, s, 10 );
   a[10] = '\0';
   printf("%s\n", a);
   strncpy( b, s+10, 6 );
   b[6] = '\0';
   printf("%s  %s\n", a, b);
   return 0;
}

结果:

0123456789
  ABCDEF

我已经预料到了

0123456789
0123456789  ABCDEF

a 怎么了?谁能告诉我怎么了?

【问题讨论】:

  • a[10] = '\0';b[6] = '\0'; 无效。

标签: c c-strings strncpy


【解决方案1】:

数组 a 和 b 不包含字符串。像这样声明它们

char a[11];
char b[7];

即为终止零字符多保留一个元素。

否则这些陈述

a[10] = '\0';
b[6] = '\0';

使用无效索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多