+ 2
Why can't I put 2 asterisks for ptr2?
int main() { float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5}; float *ptr1 = &arr[0]; float *ptr2 = ptr1 + 3; //Why not **ptr2? printf("%f ", *ptr2); printf("%d", ptr2 - ptr1); //Why the output is 3?? return 0; }
5 Respostas
+ 4
I’m still learning C myself so will welcome anyone correcting me if I’m wrong:
Firstly, an array variable name acts as a pointer to the array’s first element. You can write
float *ptr1 = arr;
and that should be fine
Next, when doing
ptr2 - ptr1
this is taking the memory address of ptr2 and subtracting from ptr1
you can do printf(“%x”... for both ptr2, ptr1 to see you are not accessing the array’s elements, you are working with the memory addresses themselves. I don’t know how 3 is calculated but even with replacing %d with %x in the subtraction printf line, I got 3 too
If I’m guessing correctly you want to subtract elements, use
*ptr2 - *ptr1
and that should do your 4th element minus the 1st element
If your question is out of curiosity how 3 is calculated, I’m not sure
But yes, you can point to a pointer.
**ptr would work if you declared
float **ptr = &ptr1
as the double asterisk means I am pointing to a pointer and &ptr1 is saying here is the address of that variable/pointer
The subtraction will then be
*ptr2 - **ptr
with the double asterisk being used to access the value (not using the memory address as is)
Without declaring **ptr, this would be using ptr1 as follows
float *ptr2 = &ptr1 + 3;
and
*ptr2 - **(&ptr1)
in the subtraction
+ 3
Thank you everybody.
+ 1
How about the ptr2? Why not **ptr2? (fifth line).