Why must int pointer be tied to variable but not char pointer?

前端 未结 8 686

I am not sure if I worded the question correctly, but here it is spelled out:

char * cp = \"this is a char pointer\";

The code above, based

相关标签:
8条回答
  • 2020-12-10 10:36

    Your understanding is correct. A string literal is really an array of char, and taking its value really yields a pointer to its first element. You can do this for any literal array (but without the syntax sugar that you have char arrays).

    char *s = "String";        // right side is array of char
    int *x = (int []){1, 2};  // right side is array of int
    

    Similarly, the following are both incorrect.

    char *s = 'S';
    int *x = 1;
    

    Note the difference between "String" and 'S'. The former is an array of char, but the latter is just an int.

    However (as was first mentioned by Keith), string literals and literal arrays (more generally called compound literals) have different storage duration. In particular, a string literal always has static storage duration; but a compound literal has automatic or static storage duration, depending if it appears in a function or not. This means that if you take a pointer to a compound literal from within a function:

    • You can read and change change it until execution goes past the end of its block, and
    • You must not access it in any way after execution goes past the end of its block. Contrary, with string literals, you can read them after that, because they have static storage.

    In this respect, taking a pointer to a literal array is very similar to just declaring an array (except, for example, sizeof()):

    int x[] = {1, 2};
    
    0 讨论(0)
  • 2020-12-10 10:38

    Strings are essentially arrays of characters. Array type (e.g char[]) variables can often be referred to as pointers (char*, pointer to beginning of an array). That means string literals are of type char* and that is why you can just assign that string to a pointer. On the other hand, integer literals, like '5' are of type int, so you cannot assign it to a pointer.

    0 讨论(0)
提交回复
热议问题