Why this code is not running? Why str1 is not assigned to str2 ?? I know i have an option of using strcpy but i wish to know the reason why this is not working??
#include<stdio.h>
int main()
{
char str1[]="hello";
char str2[10];
str2=str1;
printf("%s",str2);
return 0;
}
Whereas if I use pointers than it works like here..
#include<stdio.h>
int main()
(
char *s="good morning";
char *q;
q=s;
while(*q!='\0')
{
printf("%c",*q);
q++;
}
return 0;
}
This works.
Now the string has been copied via pointers so why such difference??
You need to do
strcpy (str2, str1)you need to copy each element of the
str1tostr2character by character.What you are doing is to attempt assign the address of the string in
str1assign to the array varstr2which is not allowed. Static arrays couldn’t be used to be assigned values.Even if you had
char *str2;and thenstr2 = str1although your code would work, but in such a case the string is not copied, instead the address of the string instr1is copied instr2so now dereferencingstr2will point to the stringAlso note that when you copy string into a
char *str2always allocate enough memory before copy.one possibility is: