Hello,
I have been looking for an answer to this for quite sometime. In my beginners book, I learned that you need to allocate memory for a string in order to use it in a program (i.e. the way I did it with var2 below, or by using an array, etc.)
However, I also tried the following. Declare a global char pointer with no initial value (i.e. like var1). In the main function, I seem to be able to assign a literal "string" to that variable without allocating memory.
Is this correct, it seems to work. I think I remember seeing somewhere that a string literal evaluates to the address it is stored at and automatically contains a '\0' at the end.
Or should this be handled by explicitly allocating like with var2?
Code:#include <stdio.h> #include <stdlib.h> char var1*; char var2*; int main( int argc, char *argv[] ) { /* assign literal string without using malloc , is this ok???, it seems to work*/ var1 = "this is a test"; /* use malloc to allocate memory */ /* test for success, then assign string */ var2 = (char *) malloc( 81 * sizeof( char ) ); if( var2 == NULL ) { puts( "couldn't get the memory!" ); exit(1); } var2 = "this is a test"; puts( var1 ); puts( var2 ); return 0; }