I was trying to concatenate 2 strings without using strcat, but I am getting a runtime error. Please, someone help me out here…
Also, is this statement q=q+len; correct? Can we add a variable to a pointer??
#include<stdio.h>
#include<string.h>
void xstrcat(char*,char*);
int main()
{
char source[]="folks";
char target[30]="hello";
xstrcat(target,source);
printf("%s",source);
printf("%s",target);
return 0;
}
void xstrcat(char*p,char*q)
{
int len=0;
len=strlen(q);
q=q+len;
while(*p!='\0')
{
*q=*p;
q++;
p++;
}
*q='\0';
}
Some mistakes in your implementation:
1 – You are accessing random memory. Once you don’t have a
/0in your string.must be:
Note the slash \.
2 – You are overwriting random memory when try to add
*pinto*q. You must create a new variable with enough space for store them.Yes. It’s a pointer arithmetic expression.