foo* one = malloc(sizeof(foo));
This allocates space for a structure object of type foo
and assigns its address to one
. This is actually better written as:
foo *one = malloc(sizeof *one);`
By not repeating the type name, you avoid possible errors if the type of the pointer ever changes.
Note that at this point the value of one->p
is garbage.
one->p = 0x5;
This is actually a constraint violation. Practically speaking, you should assume that it's illegal. one->p
is a pointer, and 0x5
is a value of type int
. There is no implicit conversion from integers to pointers (other than the special case of a null pointer constant, which doesn't apply here).
Your compiler should have at least warned you about this. In fact, any conforming C compiler is required to issue a diagnostic message. (It is, in my opinion, unfortunate that many compilers treat this as a warning rather than a fatal error by default, but there are historical reasons for that).
You could make it legal by doing a cast:
one->p = (byte_ptr)0x05;
That would store in the pointer object one->p
the result of converting the integer value 5 to a pointer value.
Unless you're doing some kind of low-level embedded programming on a system where you know what's at that specific memory address, it almost certainly doesn't make sense to do that. 0x05
, even after conversion, is unlikely to be a valid pointer value, and any attempt to use it is likely to crash your program -- if you're lucky. (If you're unlucky it will appear to "work".)
I ultimately want to set the address itself to be 0x5, not the value at that address.
If that's really what you want to do, then one->p = (byte_ptr)0x05;
is the way to do it. Why do you want to do that? What is at location 0x05 in memory?
int answer = one->p + one->num;
one->p
is a pointer, and one->num
is an integer. You can add a pointer and an integer, but the result is a pointer, and you can't assign it to an int
object without a cast. And with a cast, it very likely doesn't make sense.
If you want to store integer values, store them in integer objects.
(If you wanted to store 0x05
in the object that one->p
points to, you'd first have to arrange for it to point to something, perhaps with another call to malloc
. But that's not what you asked about, I won't go into that. Perhaps it's what you should have asked about, but I'd rather not make any assumptions.)
And if I want an int answer = 0x9, ...
Then you can write int answer = 0x9;
. I assume that's not what you're looking for, but I can't tell just what that is.
Finally, what is it you're trying to accomplish? Could it be that you have an XY problem?