hi all, i'm extremely new to C so please bare with me.
I'm currently interested in studying strings in C, since there isn't one, and malloc is one of the way, I'm not understanding when to use it.
I have two test case, which seems to say I don't need malloc at all when allocating string to array :
1. Using STRCPY needs the pointer to have an allocated size :
Code:#include<stdio.h> #include<string.h> #include<stdlib.h> int main() { char *myArray; //myArray = (char *) malloc(sizeof(myArray)); strcpy(myArray, "Hello World!"); //*** Process returned -1073741819 if no malloc*** puts(myArray); return 0; }
2. Without STRCPY, you don't need to allocate a size for a string pointer :
Code:#include<stdio.h> #include<string.h> #include<stdlib.h> int main() { char *myArray; //myArray = (char *) malloc(sizeof(myArray)); //strcpy(myArray, "Hello World!"); myArray = "Hello World!"; puts(myArray); return 0; }
why is it like that?? does that mean i can go around creating bunch of pointers as 'string datatype in C' now without allocating space?



LinkBack URL
About LinkBacks





Sorry