This is throwing a runtime error
Code:#include<studio.h> #include<string.h> int main() { const char *x="hello"; char *s=" world"; strcat(s,x); return 0; }
This is throwing a runtime error
Code:#include<studio.h> #include<string.h> int main() { const char *x="hello"; char *s=" world"; strcat(s,x); return 0; }
Because attempting to modify a string literal results in undefined behaviour, and you're doing just that by attempting to concatenate "hello" with the string literal " world". In fact, I told you in another thread:
So why did you persist in declaring s to be a pointer to non-const char? You should have declared it to be a pointer to const char, and then your mistake would have become obvious.Originally Posted by laserlight
Last edited by laserlight; 11-02-2016 at 01:36 AM.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Now even on changing the code tho this, once it had printed " worldhello" but rest of the times it said runtime error.
Code:#include<studio.h> #include<string.h> int main() { const char x[]="hello"; char s[]=" world"; strcat(s,x); printed("%s",s); return 0; }
As well as making sure you're trying to modify writeable memory, you also need to ensure you have enough memory to write to.
The compiler will measure the length of your string constants, and allocate just enough memory for s and x.Code:const char x[]="hello"; char s[]=" world"; strcat(s,x);
If you're trying to see "hello world", then your strcat parameters are the wrong way round.
Since "studio.h" and "printed" don't exist, how are you compiling this?Code:char x[30]="hello"; // 30 chars, initialised to "hello\0\0\0\0<20 more \0>\0" char s[]=" world"; strcat(x,s); // append s onto the end of x
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Despite not giving enough space to x this code is giving output as "hello world". Why?Code:char x[6]="hello"; char s[]=" world"; strcat(x,s);
> Despite not giving enough space to x this code is giving output as "hello world". Why?
Because of pure dumb luck.
I would suggest you learn how to do it properly, instead of experimenting with all sorts of undefined behaviour and wondering why various things do (or do not) happen.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.