Hi. I’m confused by pointers Nothing new there, I guess, but I have one specific misunderstanding which is getting in my way and stopping me from really understanding pointers.
I believe that a pointer is a number, and the value of that number is an address in memory, and at that address there can be a value of any type or even a whole set of values and other stuff located in contiguous memory locations starting at that address. But when I set out to test this belief, I get confusing results.
Here is some code:
int i = 17; int *j = &i; printf("i is %d\n",i); // outputs 17 printf("j is %p\n",j); // outputs 0x7fff5fbff2cc printf("address of i is %p\n", &i);// outputs 0x7fff5fbff2cc as expected
OK. so far. So I tried to set the address programmatically:
long k = 0x7fff5fbff2cc; int valueAtAddressk = *k;// This throws an error Invalid type arg of "unary *"
even though k gets through the printf call happily (apart from the warning):
printf("k is %p\n",k);// warning about format type "void *" vs type long, but still outputs 0x7fff5fbff2cc
printf("value stored at address k is %d\n",*k);// This throws the same error as above
So my belief that k stores the address of the value of i must be wrong. But if I assign k to a pointer which gives exactly the same value, it works:
int *l = k;// warning about making pointer from int without cast printf("l is %p\n",l);// outputs 0x7fff5fbff2cc printf("value stored at address l is %d\n",*l);// outputs 17
So why does *l work when *k does not?