[LCP] Newbie Question: Initializing empty/null string in C

Bill Rausch BRausch at owt.com
Mon Jun 11 15:01:23 UTC 2007


At 1:03 AM -0700 6/11/07, Ludwig Isaac Lim wrote:
>Hi:
>
>    I have a newbie question (I wasn't able to find the
>answer using google).
>
>    What is the best way to initilize an empty/null string
>in C? suppose I have a char* str, how should I initialize
>it.
>
>    char* str;
>
>    1) Approach 1 :
>          str = "";
>
>    2) Approach 2 :
>         str[0] ='\0';
>
>    3) Approach 3 :
>        strcpy(str,"");
>
>    4) Approach 4 :
>       *str = '\0';

Your question needs some context. The way you've declared it, str is 
just a pointer to something. In order to use it for anything, you'll 
need to point at something. If your goal is to have an empty string, 
then your approach #1 would work. Numbers 2, 3, and 4 should all fail 
unless you point str at something after you declare it and before you 
use it. #1 works because the compiler will allocate some space for 
the "" and then point your str variable at it. The other three assume 
str already points at a valid place.


>    I suppose there's no need to allocate a space for the
>string terminator character ('\0') using:
>    str = (char*) malloc(sizeof(char));
>    prior to initialization.
>
>
>Thanks in advance,
>ludwig lim
>
>
>       
>____________________________________________________________________________________
>Get the free Yahoo! toolbar and rest assured with the added security 
>of spyware protection.
>http://new.toolbar.yahoo.com/toolbar/features/norton/index.php
>
>_______________________________________________
>This is the Linux C Programming List
>:  http://lists.linux.org.au/listinfo/linuxcprogramming List


-- 
Bill Rausch

We first make our habits and then our habits make us. --John Dryden



More information about the linuxCprogramming mailing list