我对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;
}
Run Code Online (Sandbox Code Playgroud)
提示用户输入.假设他们输入"12345678".那么程序的输出是:
string=1234567812123456
sub1=12123456
sub2=123456
Run Code Online (Sandbox Code Playgroud)
我期待的输出如下:
string=12345678
sub1=12
sub2=123456
Run Code Online (Sandbox Code Playgroud)
我不明白strncpy似乎是如何将数字附加到字符串上...显然我不太了解strncpy,但有人可以向我解释发生了什么吗?
C字符串需要以空字符(0)终止.
strncpy不会为您在字符串上放置一个null终结符.如果你想要一个2个字符的字符串,你需要为三个字符分配空间,并将最后一个字符设置为null.
试试这个:
struct word {
char string[9];
char sub1[3];
char sub2[7];
};
// ...
strncpy(p->sub2,p->string,6);
p->sub2[6] = 0;
strncpy(p->sub1,p->string,2);
p->sub1[2] = 0;
// ...
Run Code Online (Sandbox Code Playgroud)
请注意,如果用户输入的字符多于您为其分配的空间,则最终会出现问题.
| 归档时间: |
|
| 查看次数: |
1695 次 |
| 最近记录: |