In C, why can't an integer value be assigned to an int* the same way a string value can be assigned to a char*?

后端 未结 5 902
北荒
北荒 2020-11-29 09:01

I\'ve been looking through the site but haven\'t found an answer to this one yet.

It is easiest (for me at least) to explain this question with an example.

I

5条回答
  •  抹茶落季
    2020-11-29 09:21

    In fact, you can do so using a compound literal, a feature added to the language by the 1999 ISO C standard.

    A string literal is of type char[N], where N is the length of the string plus 1. Like any array expression, it's implicitly converted, in most but not all contexts, to a pointer to the array's first element. So this:

    char *mystr = "hello";
    

    assigns to the pointer mystr the address of the initial element of an array whose contents are "hello" (followed by a terminating '\0' null character). Incidentally, it's safer to write:

    const char *mystr = "hello";
    

    There are no such implicit conversions for integers -- but you can do this:

    int *ptr = &(int){42};
    

    (int){42} is a compound literal, which creates an anonymous int object initialized to 42; & takes the address of that object.

    But be careful: The array created by a string literal always has static storage duration, but the object created by a compound literal can have either static or automatic storage duration, depending on where it appears. That means that if the value of ptr is returned from a function, the object with the value 42 will cease to exist while the pointer still points to it.

    As for:

    int *myint = 5;
    

    that attempts to assign the value 5 to an object of type int*. (Strictly speaking it's an initialization rather than an assignment, but the effect is the same). Since there's no implicit conversion from int to int* (other than the special case of 0 being treated as a null pointer constant), this is invalid.

提交回复
热议问题