Below is the program to copy the one string to another. I would expect the following program to give me a warnig or an error but it works just.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void strcp(const char *source,char *dest)
{
while(*source!='\0')
{
*dest++=*source++;
}
// *dest='\0';
}
int main(void)
{
char source[]="This is a test string";
int len=strlen(source);
char *dest = (char *)calloc(len,sizeof(char));
strcp(source,dest);
printf("\n The destination now contains ");
printf("%s",dest);
return 0;
}
Here I ve commented out *dest='\0'
So *dest doesnot contain any null character at the end of the string
But how is then the printf statement in the main function working fine cause I guess all function which involves string rely on the '\0' character to mark the end of string ?
P.S. I got the answer of my first question but none of the answer talked about this question below
And also I found it strange that i could use pointer dest directly with %s specifier in the printf I just wrote the last printf in the main to check will it work or not cause earlier i was using
char *temp=dest
while(*temp!='\0')
{
printf("%c",*test++);
}
In place of printf("%s",dest)
calloc()for this situation, you don't need to initialize all items to0because you are going to overwrite them immediately, and usingcalloc()may hide bugs from memory debuggers, also Do not cast it's return valuemalloc(and family)++is sequenced after the evaluation of the expression, isn't it?*dest++=*source++;are common in C, and also well-defined. It is completely equivalent to*dest = *source; dest++; source++;. And because the latter form is completely 100% equivalent, one should use the latter so one doesn't confuse the reader. It is good programming practice never to mix the ++ operators together with other operators, because in many other cases, doing so leads to bugs and undefined behavior.