Sunday, August 2, 2009

How do u declare a string to be null / empty in C ?

say I got a variable "char[] something = "Hello World" "


Now I want something to be empty, null. How do I do this ?

How do u declare a string to be null / empty in C ?
something.empty();
Reply:char[] something="" or char[] something=NULL. or char[] something=0.
Reply:Actually, if you are using 'C', and you just want the string to be 'empty' (i.e. still be accessable by address, but contain no characters, then you need to set the first character to '\0' (ASCII value 0) since all C strings end with a 'null' character.





Note, this is different from "NULL", which is used to initialize pointers. Now, assuming this is valid ANSI C and you used:





char something[] = "Hello World";





Then you could basically empty the string by using:





something[0] = '\0';





However, be very careful. Because you did not specify a size of the array, you will only be able to copy no more than 12 'char' values into the string (the length of "Hello World" plus its 'null' character). If you were to empty the string, then use strcpy() or other direct means to fill this string array, you would cause stack or heap corruption if you overstep that twelve char boundary.





You can do something like this:





char something[1024] = { "Hello World" };





This will ensure that you have up to 1024 characters of space (minus one for the ending null character) that you can use later to fill up with larger strings.
Reply:string is an array ends with the character \0

flowers gifts

No comments:

Post a Comment