本文介绍了通过指针实现strcat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试此代码,但它在运行时显示分段错误. 但是当我使用char s []和char t []代替main()中的char * s,char * t时,问题得到纠正.我不知道为什么吗?
I am trying this code ibut it is showing segmentation fault at run time. But when I am using char s[] and char t[] instead of char *s , char *t in main(), the problem gets rectified.I dont know why ?
void my_strcat ( char *s , char *t) {int i , j; for( i=0;s[i] !=''\0''; i++) ; for( j=0; t[j] !=''\0'';j++) s[i+j]=t[j]; s[i+j]=''\0''; cout<<"concatenated string is"<<endl<<s; } int main () { char *s="lion"; char *t="california"; my_strcat(s , t ); return 0; }推荐答案
ARopo是正确的.您必须在缓冲区中提供足够的空间以放置多余的字符. 使用此 ARopo is right. You must provide enough space in your buffer to put the extra characters. Use this char s[100] = "lion"; ...
最好提供缓冲区的长度.这称为防御性编程:
And it is always a good practice to give the length of your buffer. This is called defensive programming:
void my_strcat (char *s, int maxLength, const char *t) { if (maxLength <= 0) return; int i, j; //always make sure we don't go too far by testing the maxLength for (i = 0; i < maxLength && s[i] != '\0'; i++); for (j = 0; i + j < maxLength && t[j] != '\0'; j++) s[i + j] = t[j]; if (i + j < maxLength) s[i + j] = '\0'; else s[maxLength - 1] = '\0'; cout << "concatenated string is " << endl << s; } int main () { char s[100] = "lion"; char *t = "california"; my_strcat(s, 100, t); return 0; }
您不能复制到s,因为它已分配了字符串常量,所以没有为要添加的字符分配内存,请尝试此操作 You can''t copy to s this is assigned a string constant so has not memory allocated for the characters you are adding , try this char s[20]; s[0]=''l''; s[2]=''i''; s[3]=''o''; s[4]=''n''; s[5]=''\0''; my_strcat(s , t );
您也可能想将功能更改为
also you might want to change your function to
void my_strcat ( char *s , const char *t)
您必须为生成的字符串分配内存... you must alloc memory for resulting string ...
更多推荐
通过指针实现strcat
发布评论