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

Bradley, Peter pbradley at uwic.ac.uk
Mon Jun 11 09:33:32 UTC 2007


Approaches 2 and 4 are exactly equivalent and will work.  Approach 1
will set the address pointed to null, I think, so probably won't work
(off the top of my head).  Approach 3 looks as though it will work, but
I haven't tried it (or any of the other approaches).  It looks a bit
long winded, though.

As for allocating space, I suppose if you're allocating space
dynamically you might want to do what you're doing, but you'll have to
manage it carefully.  If you have a reasonable idea of how long the
string is going to be, you can just do:

char str[SIZE];

Where SIZE is the amount of space you want to allocate, including the
null character.

I think that's right, anyway.  No doubt someone more knowledgeable than
me will correct it if it's not.

Cheers



Peter


-----Original Message-----
From: linuxcprogramming-bounces at lists.linux.org.au
[mailto:linuxcprogramming-bounces at lists.linux.org.au] On Behalf Of
Ludwig Isaac Lim
Sent: 11 June 2007 09:04
To: linuxCprogramming at lists.linux.org.au
Subject: [LCP] Newbie Question: Initializing empty/null string in C

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';

   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



More information about the linuxCprogramming mailing list