Assign integer literal to pointer?

后端 未结 5 1897
说谎
说谎 2021-01-15 14:20

This question might be too bad but I can take risk to post this question here to address my confusion.

Actually my question is that we can only assign address to poi

相关标签:
5条回答
  • 2021-01-15 14:50

    barak manos already pointed it out in his comment:

    If you want to set a pointer to a literal value, you need to cast the literal value to the corresponding pointer type first.

    NULL could just as well be defined as (void *) 0... which is implicitly convertible to any pointer type.

    In either case, you end up with a pointer pointing to a literal address.

    In no case, however, does your pointer point to memory containing a literal 4, though. This is, to my knowledge, not possible without assigning that literal value to an int first:

    int i = 4;
    int * p = &i;
    
    0 讨论(0)
  • 2021-01-15 14:50

    In fact literal 0 or any constant value that is zero is an exception. It could assign to a pointer and it means a NULL or nullptr. In reverse, any null pointer evaluates to 0.

    Null does not point to any memory address location, its compiler's responsibility to handle it. It is null and null is nowhere in the memory. It points to nothing.

    0 讨论(0)
  • 2021-01-15 15:04

    The reason for this is different in C from C++ IIRC. In C++ 0 is special literal that, by definition, can be interpreted as a null pointer of any pointer type; so in this case there is no cast from integer to pointer. To test this you can try doing this:

    int i = 0;
    int* p = i;
    

    Which you will discover gives an error (See here for IDEOne example)

    0 讨论(0)
  • 2021-01-15 15:05

    No it does not break the rule. The integer constant 0 (and generally any constant expression evaluating to 0) is treated specially and it is allowed to assign such value to a pointer. It does not mean that you can assign any integer - just zero.

    The current version of C++ introduces the new nullptr keyword which should be used instead.

    0 讨论(0)
  • 2021-01-15 15:06

    you can directly set the address of a pointer in c:

    char * p  = reinterpret_cast<char *>( 0x0000ffff ) ;
    

    Note that is not generally considered safe use of pointers for obvious reasons (can point anywhere in memory).

    for more info see here and related question here

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