Whenever I am using one of these functions in dev-C++(I know its old but for some reason still taught at my college.)
strcat,strcpy,strcmp,strchr...//And their variants stricmp...
The first argument for these functions always has to be an array (i.e:
char ch[]="hello";
But it can’t be a pointer to a string bc for some reason this causes a crash.
In fact for an example look at both of these codes:
code1:
#include<stdio.h>
#include<string.h>
main()
{char ch[20]="Hello world!";
char *ch2="Hello Galaxy!";
strcat(ch,ch2);
printf("%s",ch);
scanf("%d")//Just to see the output.
}
This code works fine and gives the expected result(Hello World!Hello Galaxy!)
But the inverse code2 crashes.
code2:
#include<stdio.h>
#include<string.h>
main()
{char ch[20]="Hello world!";
char *ch2="Hello Galaxy!";
strcat(ch2,ch);
printf("%s",ch2);
scanf("%d")//Just to see the output.
}
This code crashes and causes a
file.exe has stopped working Error.
This is the same for almost all of the strings functions that takes two arguments.
What is the cause of this problem.
With
char *ch2 = "Hello Galaxy!";you are obtaining a pointer to a string literal. You should never attempt to modify a string literals, as this invokes undefined behaviour (which in your case has manifested as a crash).With
char ch[20] = "Hello World!";you are initialising an array using the contents of a string literal, so you end up with your own modifiable copy of the string inch.Also, note that 20 characters is not enough for
Hello World!Hello Galaxy!to fit, and this is also undefined behaviour, and known as overflowing your buffer.