相关疑难解决方法(0)

strncpy问题(C语言)

我对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 string strncpy

0
推荐指数
1
解决办法
1695
查看次数

标签 统计

c ×1

string ×1

strncpy ×1