In addition to Will Dean's version, the following are common for whole buffer initialization:
char s[10] = {'\0'};
or
char s[10];
memset(s, '\0', sizeof(s));
or
char s[10];
strncpy(s, "", sizeof(s));
Answer from Matt Joiner on Stack OverflowIn addition to Will Dean's version, the following are common for whole buffer initialization:
char s[10] = {'\0'};
or
char s[10];
memset(s, '\0', sizeof(s));
or
char s[10];
strncpy(s, "", sizeof(s));
You want to set the first character of the string to zero, like this:
char myString[10];
myString[0] = '\0';
(Or myString[0] = 0;)
Or, actually, on initialisation, you can do:
char myString[10] = "";
But that's not a general way to set a string to zero length once it's been defined.
c - Initializing a string with the empty string - Stack Overflow
C string initialization - undersized | The FreeBSD Forums
[Caesar]How to declare an empty string array in C?
Proper way to initialize a string in C - Stack Overflow
Videos
I know that some compilers give error on following:
char* test2;test2 = "";
Is it valid or equivalent, to do the following?
char* test2;test2[0] = '\0';
Thank in advance for your response.
Well it's sort of possible, but it won't behave the way you expect. And in more recent versions of C, it's undefined behaviour.
What you did was allocate memory and then throw that pointer away, thus leaking that memory. You replaced the pointer with a non-constant pointer to a string literal (which should make your compiler emit a warning or an error).
This happened to work in your case. Fortunately you didn't try to write to that memory. If you did, chances are that bad stuff will happen.
Uh, oh! You allocate memory for a string and store the handle to the allocated memory in w:
char* w = malloc(100*sizeof(char));
In the next line, you overwrite that handle with an immutable string literal:
w = "";
That means that (1) you can no longer free w as you should after using it and (2) that w now points to a string in read-only memory whose modification will lead to undefined behaviour, most likely a crash.
The dynamically allocated memory behaves like an array. C strings are character arrays that contain the valid characters of the string up to a null terminator, '\0'. There fore, setting the first character to the null character will give you an empty string:
*w = '\0';
or
w[0] = '\0';
In the dead branch, you want to fill the character array with the contents of a string, but you assign a read-only literal, too. You can use the function strcpy from <string.h> to fill a character array with a string:
strcpy(w, "Not empty anymore");
You must make sure, however, that the array is big enough to hold the string plus the terminating null character.
How do I initialize it to anything other than zero or NULL? I just want an empty string array, which I can use to store text with the help of a for loop. I dont want to assign it the function of GetString. If I declare the array in between an operation like.
string c_txt[i] = (p_txt[i] + key) % 26;
where c_txt is the array containing enciphered text, p_txt is array containing plain text, the console pops me an error saying "variable-sized object may not be initialized".
Also, string c_txt = NULL; desent work for obvious reasons. So how do I declare this string array?
P.S : I have a really bad feeling that this is a really dumb question and I`m making a fool of myself in front of the staff. What am I missing?
You're supposed to set it before using it. That's the only rule you have to follow to avoid undefined behaviour. Whether you initialise it at creation time or assign to it just before using it is not relevant.
Personally speaking, I prefer to never have variables set to unknown values myself so I'll usually do the first one unless it's set in close proximity (within a few lines).
In fact, with C99, where you don't have to declare locals at the tops of blocks any more, I'll generally defer creating it until it's needed, at which point it can be initialised as well.
Note that variables are given default values under certain circumstances (for example, if they're static storage duration such as being declared at file level, outside any function).
Local variables do not have this guarantee. So, if your second declaration above (char *str;) is inside a function, it may have rubbish in it and attempting to use it will invoke the afore-mentioned, dreaded, undefined behaviour.
The relevant part of the C99 standard 6.7.8/10:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
- if it has pointer type, it is initialized to a null pointer;
- if it has arithmetic type, it is initialized to (positive or unsigned) zero;
- if it is an aggregate, every member is initialized (recursively) according to these rules;
- if it is a union, the first named member is initialized (recursively) according to these rules.
I'm wonder, what is the proper way of initializing a string?
Well, since the second snippet defines an uninitialized pointer to string, I'd say the first one. :)
In general, if you want to play it safe, it's good to initialize to NULL all pointers; in this way, it's easy to spot problems derived from uninitialized pointers, since dereferencing a NULL pointer will yield a crash (actually, as far as the standard is concerned, it's undefined behavior, but on every machine I've seen it's a crash).
However, you should not confuse a NULL pointer to string with an empty string: a NULL pointer to string means that that pointer points to nothing, while an empty string is a "real", zero-length string (i.e. it contains just a NUL character).
char * str=NULL; /* NULL pointer to string - there's no string, just a pointer */
const char * str2 = ""; /* Pointer to a constant empty string */
char str3[] = "random text to reach 15 characters ;)"; /* String allocated (presumably on the stack) that contains some text */
*str3 = 0; /* str3 is emptied by putting a NUL in first position */