Reputation: 375
char *p = "a";
is valid but not int *p = 2;
and char *p = 'a';
Why are they designed like that?
Upvotes: 2
Views: 225
Reputation: 58271
A typeof string literal is of char[n]
and assignment to char*
is fine.
Point is both are pointers.
char *p = "a";
means p
points to string "a"
(some where in memory, type of "a"
is char[2]
).
p 23 24
+----+ +----+----+
| 23 | | a | \0 |
+----+ +----+----+
Whereas 2
and 'a'
are of int type values, not a valid address hence following declarations are errors/warnings: "initialization makes pointer from integer without a cast"
int *p = 2; and
char *p = 'a';
note: in c a char constant is int type, but not char refrence.
Upvotes: 3
Reputation: 239861
Because "a"
has a type of char *
, and 2
doesn't have a type of int *
. Note that char *p = 'a'
is also invalid.
Upvotes: 1
Reputation: 6606
Anything wrritten inside " "
is considered as string in C.So
char *p = " a"
says you are passing base address of string to char pointer.which is Valid.
int *p
says p
is a pointer to integer so p
can hold a address to integer so int *p = 2
is not valid.
Similarly char *p
is pointer to character so p
can hold address of a character so char *p = 'a'
is not valid because 'a'
is just a character not address to character.
Upvotes: 4