我是C语言的新手,我在使用strcat()时遇到问题。我查了一下strcat,发现它以字符串作为参数,但是当我从char数组中拆分项目时,它是一个char,当我将其用作strcat的参数时,它会打印出错误。
#include <stdio.h>
#include <string.h>
int main()
{
char a[10]="abcdefg123";
char *pa=a;
char *out[2]={"",""};
int counter=0;
while(*pa != '\0'){
if (counter%2==0){
strcat(out[0],*pa);
}
else{
strcat(out[1],*pa);
}
counter++;
pa++;
}
printf("%s,%s\n",out[0],out[1]);
return 0;
}
代码的目的是将一个字符串分成两个字符串,每个字符串包含所有在奇数位置或偶数位置的字符。但是,当我试图取消对char指针的引用时,我得到的只是一个Char,但似乎我需要一个字符串
使用中的临时字符串strcat
代替strcat(out[0],*pa);
。
另外,请确保为分配了足够的内存out
。
int main()
{
char a[10]="abcdefg123";
char temp[2] = {0};
char *pa=a;
// This is not good for `strcat`.
// char *out[2]={"",""};
// Use this instead.
char out[2][20]={"",""};
int counter=0;
while(*pa != '\0'){
temp[0] = *pa;
if (counter%2==0){
strcat(out[0], temp);
}
else{
strcat(out[1], temp);
}
counter++;
pa++;
}
printf("%s,%s\n",out[0],out[1]);
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句