I have been trying to understand what is malloc() and why is it used. I understand that malloc is for dynamic allocation of memory, it is needed if you don't know how much memory you wan't to create. I have been doing some hands-on on it.
The following code declares an array of character pointers, and 1st character pointer is initialized with "hello". This works fine.
int main()
{
char *strarray[5];
strarray[0]="hello";
printf("%s\n",strarray[0]);
return 0;
}
But if i try to use strcpy() function to copy "hello" string into strarray[0] (without malloc()) it gives a problem. And it goes into some loop and does not copy the string. And it works fine if i use malloc to allocate memory.
int main()
{
char *strarray[5];
//strarray[0]=(char *)malloc(sizeof(char)*10);
strcpy(strarray[0],"hello");
printf("%s\n",strarray[0]);
return 0;
}
I want to know what makes the difference? If i can initialize "hello" to a char pointer for which malloc is not used, why can't i do the same with strcpy().