[Lumiera] TimelineZoomScale Question About Pointers

Odin odin.omdal at gmail.com
Sun Oct 9 11:03:02 CEST 2011


On Sun, Oct 9, 2011 at 2:16 AM, Ichthyostega <prg at ichthyostega.de> wrote:
> As elaborated above, it depends on what is left of the operator
> - when it's a value (or a value aliased through a reference) then use '.'
> - when it's an address (pointer) then you need to dereference with '->'

When you have:

void hey(struct my_struct *my_pointer);

my_pointer will point to that struct. So when you use "my_pointer".
You will in fact just get the *address* of where the my_struct you're
referring to lies. Let's say that's 0xAAA. So, my_pointer itself is a
value 0xAAA, that lies on it's own memory address. You can even do
&my_pointer, and you will get the address of where the literal value
0xAAA is stored in memory. Let's say that's 0x999.

Lastly, we're dealing with the struct itself, which is probably the
most interesting thing we've got. We know that it's stored at 0xAAA,
but there's litte use for us to print that value out, we want to USE
that address to GET at what's there. Not just get the address.

So, how do we tell the compiler to use the value to do a lookup in
memory? You "dereference" it, like so:

*my_pointer

And that will in fact give us whatever lies at the memory address
0xAAA. Let's say the value 0x3. Cool. But this is a struct, we want to
use the attributes, so how do we do that?

We can dereference the pointer, and then use the struct lookup method:

    (*my_pointer).length      gives us 0x3
    (*my_pointer).data         gives us 'h'

Doing that brings some pain. Let's do a totally cramped and bad
example (code you'd never write):

    for (int i=0; i < (*my_pointer).length; i++)
       printf("%s", (*my_pointer).data[i]);

    printf("\n");

That will print out 'hey\n'.

So. Going on with all those parantheses is boring stuff, we don't want
to do that because dereferencing a pointer and looking up stuff at
that address is such a common thing to do that they put some syntactic
sugar on top of it to make it a bit more beautiful.

So using -> is totally equivalent:

    my_pointer->length      gives us 0x3
    my_pointer->data         gives us 'h'

and:

    for (int i=0; i < my_pointer->length; i++)
       printf("%s", my_pointer->data[i]);

    printf("\n");


So, my_pointer is stored at address 0x999, and it's literal value is: 0xAAA.
my_struct is stored at address 0xAAA, and it's literal value is: 0x03
(and it's 4 long, so also 'h', 'e', 'y' are stored in 0xAAB, 0xAAC and
0xAAD).



There might be errors, I'm mostly a javascript/python guy, I only
remember this stuff from my asm days :-)

-- 
Beste helsing,
Odin Hørthe Omdal <odin.omdal at gmail.com>
English, technical: http://tech.velmont.net
Norsk, personleg: http://velmont.no


More information about the Lumiera mailing list