Declare and initialize pointer concisely (i. e. pointer to int)

前端 未结 4 961
陌清茗
陌清茗 2020-11-29 10:29

Given pointers to char, one can do the following:

char *s = \"data\";

As far as I understand, a pointer variable is declared here, memory i

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 11:12

    String literals are a corner case : they trigger the creation of the literal in static memory, and its access as a char array. Note that the following doesn't compile, despite 42 being an int literal, because it is not implicitly allocated :

    int *p = &42;
    

    In all other cases, you are responsible of allocating the pointed object, be it in automatic or dynamic memory.

    int i = 42;
    int *p = &i;
    

    Here i is an automatic variable, and p points to it.

    int * i;
    *i = 42;
    

    You just invoked Undefined Behaviour. i has not been initialized, and is therefore pointing somewhere at random in memory. Then you assigned 42 to this random location, with unpredictable consequences. Bad.

    int *i = malloc(sizeof *i);
    

    Here i is initialized to point to a dynamically-allocated block of memory. Don't forget to free(i) once you're done with it.

    int i = 42, *p = &i;
    

    And here is how you create an automatic variable and a pointer to it as a one-liner. i is the variable, p points to it.

    Edit : seems like you really want that variable to be implicitly and anonymously allocated. Well, here's how you can do it :

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

    This thingy is a compound literal. They are anonymous instances with automatic storage duration (or static at file scope), and only exist in C90 and further (but not C++ !). As opposed to string literals, compound literals are mutable, i.e you can modify *p.

    Edit 2 : Adding this solution inspired from another answer (which unfortunately provided a wrong explanation) for completeness :

    int i[] = {42};
    

    This will allocate a one-element mutable array with automatic storage duration. The name of the array, while not a pointer itself, will decay to a pointer as needed.

    Note however that sizeof i will return the "wrong" result, that is the actual size of the array (1 * sizeof(int)) instead of the size of a pointer (sizeof(int*)). That should however rarely be an issue.

提交回复
热议问题