The code was to copy and concatenate strings widout using library functions.the code i used:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 100
char* newStrCpy(char string1[],char string2[])
{
int i=0;
while(string1[i]!='\0')
{
string2[i]=string1[i];
i++;
}
return (string2);
}
char* newStrCat(char destination[],char arr[])
{
int a=0;
int destlen=0;
while(destination[destlen]!='\0')
{
destlen ++;
}
while(a<(MAX-destlen))
{
destination[(destlen+a)]=arr[a];
a++;
}
return destination;
}
void main()
{
char string1[MAX],string2[MAX];
int i=0,j=0;
char bak[5]="\n is";
char som[50]=" the concatenated array.";
fflush(stdin);
printf("Enter a string:\n");
scanf("%[^\n]s",&string1);
newStrCpy(string1,string2);
printf("The copied string is:\n");
while(string2[i]!='\0')
{
printf("%c",string2[i]);
i++;
}
newStrCat(string2,bak);
newStrCat(string2,som);
printf("\nThe conctenated string is:\n");
while(string2[j]!='\0')
{
printf("%c",string2[j]);
j++;
}
fflush(stdout);
getch();
}
and the output i got:
Enter a string:
Welcome!!
The copied string is:
Welcome!!
he concatenated string is:
Welcome!!
is the concatenated string
You need to initialize your
string2array:This ensures all members are set to
\0[Ref #1] and you don’t have to bother appending a\0manually to your string array, after copying.Currently, your
string2array is never null terminated and hence thewhileloop continues till it encounters a\0and it outputs garbage which is not a part of your string.Also on a side note,
makes your program have the beast of Undefined Behavior, do not use it.
fflush()is guaranteed to work on output streamstdout.[Ref #1]
C99 Standard 6.7.8.21