Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assign any integer value to a pointer variable directly?

Tags:

c

Since addresses are numbers and can be assigned to a pointer variable, can I assign any integer value to a pointer variable directly, like this:

int *pPtr = 60000;
like image 456
Kristina Avatar asked Oct 19 '25 21:10

Kristina


1 Answers

You can with an explicit cast:

int *pPtr = (int *)60000;

But unless you're developing for an embedded device with known memory addresses with a compiler that explicitly allows it, attempting to dereference such a pointer will invoke undefined behavior.

You should only assign the address of a variable or the result of a memory allocation function such as malloc, or NULL.

like image 72
dbush Avatar answered Oct 21 '25 12:10

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!