简体   繁体   English

使用 strncpy 将字符串的两个部分复制到其他两个字符串

[英]Copy two parts of a string to two other strings using strncpy

I want to copy two parts of string s to two strings a and b:我想将字符串 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;
}

Result:结果:

0123456789
  ABCDEF

I had expected我曾预料到

0123456789
0123456789  ABCDEF

What has happened to a? a 怎么了? Can anybody tell me what is wrong?谁能告诉我有什么问题?

The arrays a and b do not contain strings. arrays a 和 b 不包含字符串。 Declare them like像这样声明它们

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

that is reserve one more element for the terminating zero character.即为终止零字符多保留一个元素。

Otherwise these statements否则这些陈述

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

use invalid indices.使用无效索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM