Originally Posted by
tennisstar
and yes.. by "Why doesn't it work for int?" i meant why cant you do int* a = 1213 like that... and why can you do it to char like char* a = "tennisstar"
Ah. You're asking about the infamous anomaly of C.
Firstly, it doesn't make sense to do "int *a = 1213" any more than it makes sense to do "char *c = ' '" (note the single quotes in the char example). Both are invalid, and will cause a compiler to complain, for the same reason. It makes no sense to convert an int value (1213) into a pointer, and also makes no sense to convert a char value (' ', which is 32 with the ASCII character set) into a pointer.
But, to come to your question, the handling of char strings to initialise char pointers is actually a historical anomaly in the language. Originally, in early versions of C (I'm not sure if this predated K&R C, or was originally part of K&R C) it was never valid to initialise a pointer using an array.
At that time, these constructs were valid
Code:
int ai[] = {1,2,3};
int *pi = i; /* equivalent to int *pi = &ai[0] */
char ac[] = "xy"; /* equivalent to char ac[] = {'x', 'y', '\0'} */
char *pc = c;
but these constructs were not valid
Code:
int *pi = {1,2,3};
char *pc = "xy";
This is how it was, and compilers were shipped. Programmers, if they wanted a pointer that was initialised so it contained the first address of a char literal, were forced to do
Code:
char *ac[] = "xy";
char *pc = ac;
/* code that uses pc but never again references ac */
A few too many programmers at the time were zealots of terse code, so they thought it made sense to do
Code:
char *pc = "xy";
/* code that uses pc */
and their compilers complained bitterly about this. Those programmers then lobbied their compiler vendors to allow this to happen. However, the same programmers caused some bemusement for their compiler vendors by insisting that
should still be invalid.
Hence, today, we have an anomaly in the C language. Character pointers can be initialised directly using a string literal, but pointers to other types cannot be initialised using an array initialiser.
The reason for this anomaly is purely non-technical. In fact, it was quite political, and the arguments in favour of the anomaly often amounted to religious fervour (from those who worship at the altar of terseness).