通过实施指针的strcat [英] Implementing strcat using pointers
问题描述
虽然做琴弦上的一些程序,我所遇到的这个小问题。
其中有人问我是这样的问题 -
编写函数strcat的(S,T),它的字符串复制吨至年代末的一个指针版本。
我写的程序,因为这 -
While doing some programs on strings, I have come across this little problem. The question which was asked to me was this - Write a pointer version of the function strcat(s,t) which copies the string t to the end of s. I wrote the program as this -
#include<stdio.h>
void strcat(char *s, char *t);
int main()
{
char *s1, *s2;
printf("enter the first string\n");
scanf("%s",s1);
printf("Enter the second string\n");
scanf("%s",s2);
strcat(s1,s2);
printf("Strings concatenated\n");
printf("%s",s1);
return 0;
}
void strcat(char *s, char *t)
{
while(*s++)
;
while(*s++ = *t++)
;
}
我知道我做了什么(或很多事情)可怕的错误。因为每当我试图C-它给了我分割故障运行此$ C $。这样的 -
I know i have done something(or many things) terribly wrong. Because whenever i try to run this code- it gives me segmentation fault. Like this-
输入第一个字符串
您好
输入第二个字符串
分割故障(核心转储)
这将是非常有益的,如果有人点了我的执行缺陷/瑕疵。先谢谢了。
It would be really helpful if someone points me out the flaw/flaws of my implementation. Thanks in advance.
非常感谢你的家伙,对于这样的快速反应。但似乎这不是唯一的问题。写这样的程序后 -
Thank you very much guys, for such quick responses. But seems that wasn't the only problem. After writing the program like this-
#include<stdio.h>
void strcat(char *s, char *t);
int main()
{
char s1[20], s2[20];
printf("enter the first string\n");
scanf("%s",s1);
printf("Enter the second string\n");
scanf("%s",s2);
strcat(s1,s2);
printf("Strings concatenated\n");
printf("%s",s1);
return 0;
}
void strcat(char *s, char *t)
{
while(*s++)
;
while(*s++ = *t++)
;
}
它运行这样的。
输入第一个字符串
您好
输入第二个字符串
有
您好
它只打印我已经进入了第一个字符串。现在,我想我已经上作出了strcat的功能有一定的错误了。
It only prints the first string i have entered. Now i think i have made some mistake on that strcat function too.
推荐答案
1)在的main()
,你必须为分配内存 S1
和 S2
指针
1) In the main()
, you have to allocate memory for both s1
and s2
pointers
char *s1=malloc(100*sizeof(char)), *s2=malloc(100*sizeof(char));
scanf("%99s",s1); //the "%99s" allow to avoid buffer overflow
如果你使用gcc和你的gcc> 2.7,那么你可以在 scanf函数使用%MS()
是这样的:
scanf("%ms",&s1);
与%MS
的 scanf()的
将分配内存 S1
指针
2),你必须添加秒 -
在
while(*s++)
;
s--; // add s-- here
while(*s++ = *t++)
;
因为s指向在的'\\ 0'
元素的下一个元素指向。在S指针应该指出的'\\ 0'
元素开始复制第二个字符串之前
because the s pointer is pointing in the next element of '\0'
element. the s pointer should be pointed in the '\0'
element before starting copy the second string
这篇关于通过实施指针的strcat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!