通过指针实现strcat

编程入门 行业动态 更新时间:2024-10-27 23:27:56
本文介绍了通过指针实现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

本文发布于:2023-07-29 06:40:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1238187.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   strcat

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!