我在使用 strncpy 时遇到了困难。我正在尝试将 8 个字符的字符串一分为二(一个子字符串中的前 6 个字符,然后在另一个子字符串中剩余 2 个字符)。为了说明特别困难,我将代码简化为以下内容:
include stdio.h
include stdlib.h
include string.h
define MAXSIZE 100
struct word {
char string[8];
char sub1[2];
char sub2[6];
};
typedef struct word Word;
int main(void)
{
Word* p;
p=(Word*)malloc(MAXSIZE*sizeof(Word));
if (p==NULL) {
fprintf(stderr,"not enough memory");
return 0;
}
printf("Enter an 8-character string: \n");
scanf("%s",p->string);
strncpy(p->sub2,p->string,6);
strncpy(p->sub1,p->string,2);
printf("string=%s\n",p->string);
printf("sub1=%s\n",p->sub1);
printf("sub2=%s\n",p->sub2);
free(p);
return 0;
}
提示用户输入。假设他们输入“12345678”。那么程序的输出是:
string=1234567812123456
sub1=12123456
sub2=123456
我期望的输出如下:
string=12345678
sub1=12
sub2=123456
我不明白 strncpy 似乎如何将数字附加到字符串......显然我对 strncpy 的理解不够好,但谁能向我解释发生了什么?