我正在尝试从一个字符串读取两个连续的字符,并将两个两个字符传递给另一个字符串。下面的代码,但它给我分段错误!我究竟做错了什么?
char *st = malloc(16*sizeof(char));
char *string = "purpleredblue";
int i;
int x=0;
while(x<=16)
{
for(i=x;i<=x+2;i++)
{
*st++=*string++; //copies content from string to st
}
x+=2;
}
printf("%s\n",st);
您的代码是完全错误的。这可能会有所帮助:
char *buffer = (char*)malloc(16 * sizeof(char));
char *source = "purpleredblue";
char *dst = buffer;
char *src = source;
char *end = source + strlen(source);
while (src <= end)
{
strncpy(dst, src, 2);
dst += 2;
src += 2;
}
printf("%s", buffer);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句