Reputation: 137
I dont know if that a string or an array...
char str4[100] = { 0 };
That code is a string?
If yes what it printing?
Upvotes: 1
Views: 190
Reputation: 206627
I dont know if that a string or an array...
It is definitely an array. It can also be a string since a string is an array of characters terminated by a null character in C.
You can use it as an array:
char str4[100] = { 0 };
str4[0] = 'a';
You can also use it as a string:
if ( strcmp(str4, "ABC") == 0 )
{
// This string contains "ABC"
}
When an array of characters is not a string
You can create an array of characters that cannot be used like a string.
char str[4] = { 'a', 'b', 'c', 'd' };
if ( str[0] == 'a' ) // OK
{
// Do something
}
if ( strcmp(str, "ABC") == 0 ) // Problem. str does not have a null character.
// It cannot be used like a string.
{
}
Upvotes: 3
Reputation: 76405
str4
is an array of char
's, so yes: it can be a string. You're initializing it to {0}
. This means the first element in the array is being initialized to a terminating nul character (the end of a string), the result being: str4
is a valid, albeit empty, string. Implicitly, the rest of the array will be initialized to 0, too BTW.
Printing this string is the same as printing an empty string:
printf("");
The code you posted is exactly the same as this:
char str4[100] = "";
//or this
char str4[100] = {0, 0, '\0'};//'\0' is the same as 0
//or even
char str4[] = {0, 0, ..., 0};//100 0's is just a pain to write...
Or, in case of a global variable:
char str4[100];
simply because objects that have static storage are initialized to their nul-values (integer compatible types are initialized to 0, pointers to NULL
):
If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.
Either way, the short answer is: str4
is an empty string.
Upvotes: 2
Reputation: 7020
In C a string is just an array of bytes that follows a particular convention, namely that the array of bytes be terminated by a null character. In this case, if you try to print str4
with something like printf
, you'll find it looks like an empty string because the first byte is a null character, terminating it immediately.
Upvotes: 1
Reputation: 145859
By definition in C a string is a contiguous sequence of characters terminated by and including the first null character. So here you array also represents a string of length 0
.
Upvotes: 1