Home > OS >  Whats the difference between int *p=10 and int *p = (int *)10?
Whats the difference between int *p=10 and int *p = (int *)10?

Time:11-20

Do both statements mean the same thing that p is pointing at address location 10? On compilation, the first initialization gives some warning. What's the meaning of that?

#include <stdio.h>
int main()
{
    int *p = 10;
    int *q = (int *)10;

    return 0;
}

output:

warning: initialization of ‘int *’ from ‘int’ makes pointer from integer without a cast [- Wint-conversion]

CodePudding user response:

Both cases convert the integer 10 to a pointer type which is used to initialize an int *. The cast in the second case makes it explicit that this behavior is intentional.

While converting from an integer to pointer is allowed, the assignment operator (and by extension, initialization) does not specifically allow this conversion, so a cast it required to be conforming. Many compilers however will still allow this and simply issue a warning (as your apparently does).

Note however that actually attempting to use a pointer that is assigned a specific numeric value will most likely cause a crash unless you're on a embedded system that supports reading or writing specific memory addresses.

CodePudding user response:

int *p = 10; is incorrect (constraint violation), and the compiler must produce a diagnostic message. The compiler could reject the program, and there is no behaviour defined if it doesn't. The rule is that the initializer for a pointer must be a compatible pointer value or a null pointer constant.

int *q = (int *)10; means to convert the integer 10 to a pointer. The result is implementation-defined and it could be a trap representation, meaning that the initialization causes undefined behaviour if execution reaches this line.

CodePudding user response:

int and pointer to an integer int* are different types. The 10 on the first line is an int that you are trying to assign to a pointer to int type. Hence the warning. (on X86 both share the same size, but consider that mostly coincidence at this point).

By casting the int to a pointer, like you do on the second line, you are telling the compiler "Hey, I know these are different types but I know what I'm doing, so go ahead and just treat the value 10 like a pointer because I really do want to point at the memory with an address of 10". (in almost every case the memory address of 10 is not going to be usable by you)

  • Related