Reputation: 193
I was trying to implement strcat
by myself, It seems to work but I don't understand how come p
has '\0'
at its end? it didn't copy it from b and it shouldn't be there without putting it. Any explanation? The output is "yesMichaelJudy".
#include<string.h>
#include<stdio.h>
#include <stdlib.h>
#include<conio.h>
char* strcat1( char *s1, const char *s2 )
{
register char *p = s1;
while ( *p )
++p;
while (*s2){
*p=*s2;
++p;
++s2;
}
if (*p=='\0') printf("yes");
++p;
p='\0';
return s1;
}
int main(){
char* a;
char* b;
char* result;
result=(char *)calloc(20,sizeof(char));
a=(char *) calloc(20,sizeof(char));
b=(char *) calloc(20,sizeof(char));
strcpy (a,"Michael");
strcpy (b,"Judy");
result=strcat1(a,b);
printf(result);
getch();
return 1;
}
Upvotes: 1
Views: 979
Reputation: 81724
You're allocating the space larger than it needs to be and you're using calloc() which by definition clears all the characters to zero; therefore the extra characters at the end are zero.
Upvotes: 4
Reputation: 320719
p
in your strcat1
points into the array passed through parameter s1
. And parameter s1
corresponds to argument a
in main
. The content of array a
in main is filled with data by strcpy (a,"Michael")
. This is what put that '\0'
at the end of that data. strcpy
did that. (You can also say that that '\0'
came from "Michael"
since "Michael"
also has a '\0'
at the end, even if it is not specified explicitly).
Upvotes: 0
Reputation: 749
calloc zero initializes ( ie fills it with NUL or '\0') the allocated buffer.
Upvotes: 0
Reputation: 9162
p='\0';
That's nonsense. It does nothing useful. It will also generate at least a compiler warning if not an error. The code should be
*p='\0';
Which is what puts \0 at the end of the string.
Upvotes: 1
Reputation: 19526
strcpy() null-terminates the string. But even if it didn't, calloc() puts it there. calloc() zeroes out the allocated memory. As soon as you allocated the memory, a and b are just a bunch of string-terminators.
Upvotes: 0
Reputation: 490623
strcpy
copies the NUL character at the end of a string. Even if it didn't, you're using calloc
to allocate your a
and b
, and calloc
allocates and zeros the memory. Since you're allocating more space than you use (allocating 20 bytes, using 4 for Judy
and 7 for Michael
) you have some zero bytes after the strings anyway.
Upvotes: 2