Reputation: 75
Consider this snippet
char a[]="";
Will a NULL
-pointer be assigned to the a character pointer *a
?
If not how do I check that the no string has been assigned to a
?
Upvotes: 0
Views: 80
Reputation: 12679
==> Will a NULL-pointer be assigned to the a character pointer *a
?
Arrays are not pointers.
For better understanding, lets refer an example from C Standard#6.7.9p32 [emphasis mine]
EXAMPLE 8 The declaration
char s[] = "abc", t[3] = "abc";
defines ''plain'' char array objects
s
andt
whose elements are initialized with character string literals. This declaration is identical tochar s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };
The contents of the arrays are modifiable. On the other hand, the declaration
char *p = "abc";
defines
p
with type ''pointer to char'' and initializes it to point to an object with type ''array of char'' with length 4 whose elements are initialized with a character string literal. If an attempt is made to usep
to modify the contents of the array, the behavior is undefined.
So, this statement
char a[]="";
defines char
array object a
whose elements are initialized with character string literal ""
. Note that ""
is a string literal containing a single character '\0'
.
The above statement is equivalent to
char a[] = {'\0'};
If we omit the dimension, compiler computes it for us based on the size of the initializer (here it will be 1
because initializer is only having one character '\0'
). So the statement is same as
char a[1] = {'\0'};
Upvotes: 0
Reputation: 70951
Will a NULL pointer be assigned to the a character pointer *a?
There is no character pointer here, but an array a
of char
.
a
will be defined as an array of char
and initialised to hold an empty-string, that is a c-string with just carrying the 0
-terminator, which is one char
.
how do I check that the no string has been assigned to a?
So a
will have exactly one element. This element compares equal to '\0'
, which in turn compares equal to 0
.
To test this do
#include <stdio.h> /* for puts() */
#include <string.h> /* for strlen() */
int main(void)
{
char a[] = ""; /* The same as: char a[1] = ""; */
/* Possibility 1: */
if (0 == a[0]) /* alternatively use '\0' == a[0] */
{
puts("a is an empty string.");
}
/* Possibility 2: */
if (0 == strlen(a))
{
puts("a has length zero.");
}
}
Upvotes: 1
Reputation: 134346
First of all, a
is not a character pointer, it is an array of char
. There are some cases where the latter is converted to the former, but they are inherently not the same type.
That said, in this initialization, array a
will be initialized with an empty string.
Empty string means, the first element will be the terminating null character, so the easiest way to check if an array contains an empty string is to compare the first element with null, like
if (a[0] == '\0') { /*do the action*/ }
Upvotes: 0
Reputation: 36483
a
will contain 1 element:
a[0] == '\0'
Note: a
is not a pointer.
Upvotes: 0