strncpy问题(C语言) [英] strncpy question (C language)

查看:98
本文介绍了strncpy问题(C语言)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用strncpy时遇到困难.我正在尝试将8个字符的字符串一分为二(一个子字符串中的前6个字符,然后另一个子中的其余2个字符).为了说明特殊的困难,我将代码简化为以下内容:

I'm having difficulty with strncpy. I'm trying to split a string of 8 characters in two (the first 6 characters in one substring and then the remaining 2 characters in another). To illustrate the particular difficulty I have simplified my code to the following:

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".程序的输出为:

The user is prompted for an input. Suppose they input "12345678". Then the output of the program is:

string=1234567812123456  
sub1=12123456  
sub2=123456

我期望的输出如下:

string=12345678  
sub1=12  
sub2=123456

我不明白strncpy似乎在字符串后面加上数字...显然我不太了解strncpy,但是有人可以向我解释发生了什么吗?

I don't understand how strncpy seems to be appending numbers to string... Obviously I don't understand strncpy well enough, but can anyone explain to me what's going on?

推荐答案

C字符串需要以空字符(0)终止.

C strings need to be terminated with a null character (0).

strncpy 不会为您的字符串添加空终止符.如果要使用2个字符的字符串,则需要为3个字符分配空间,并将最后一个设置为null.

strncpy does not put a null terminator on the string for you. If you want a 2-character string, you need to allocate room for three characters, and set the final one to 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;
// ...

请注意,如果用户输入的字符数超出了您分配的空间,那么您最终会遇到问题.

Note that if the user inputs more characters than you've allocated room for, you'll end up with problems.

这篇关于strncpy问题(C语言)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆