I am facing some problems trying to understand the difference in handling strings when they are declared as a char array and when they are declared with a pointer pointing to them. In the following code snippets, I have a few doubts.
1.While code 1 works correctly, code 2 crashes on Dev-c++ compiler.
2.Why is it that I cannot use assignments like *s = *p or *s++ = *p++ in code 2 when I have declared s and p as pointers pointing to the respective strings. And how is it valid when using s and p as arrays. in both cases dont s and p point to the first element of their respective strings? and doesnt incrementing them mean going to the next character memory location. why does the assignment not work.?
using library function, strcpy, also crashes the compiler for code 2.
code:1
#include<stdio.h>
void strc(char *s,char* p);
main()
{
char s[] = "Anime Otaku";
char p[] = "Bay Harbour butcher";
strc(s,p);
getch();
}
void strc(char *s,char *p)
{
char *t,*x;
t = s;
x = p;
printf(s);
printf(p);
while ((*s++ = *p++))
;
s = t;
p = x;
printf(s);
}
code:2
#include<stdio.h>
void strc(char *s,char* p);
main()
{
char *s = "Anime Otaku";
char *p = "Bay Harbour butcher";
strc(s,p);
getch();
}
void strc(char *s,char *p)
{
char *t,*x;
t = s;
x = p;
printf(s);
printf(p);
while ((*s++ = *p++))
;
s = t;
p = x;
printf(s);
}