On 27 Jan 2009, at 23:07, Graham Cox wrote:


On 28 Jan 2009, at 2:24 am, Jeremy Pereira wrote:

Yes. That is correct, but since buffer is already a pointer to the first byte of the array and then you are taking a reference to it, key will end up containing the address of the buffer. You really need:

uint key = *(uint*)buffer;



That's incorrect. Or rather, in this case it doesn't make any difference, but the use of '&' is more general as it works whether buffer is an array or not.


When you declare:

uint8 buffer[8];

You've reserved 8 bytes on the stack. Whether you use 'buffer' or '&buffer' you obtain the same address, as C treats array variables as pointers. But:

Having tried it just now, I stand corrected.

However, I would argue that this is the C compiler behaving in a deliberately inconsistent way, since in C, arrays and pointers are supposed to be the same thing. As buffer is actually a constant, taking its address should really result in a compiler error in the same way as int a = &123;





uint8 buffer;

You get very different results from 'buffer' and '&buffer' so in the interests of defensive programming, using '&' is allowing your code to tolerate a change to the buffer declaration without breaking. Because of the additional cast *(int*) such a change would go unnoticed by the compiler but probably have a very bad outcome at runtime. It's a good habit IMO to always take the address in these cases to make it clear in your code what your intentions were when you wrote it.

I disagree.  Consider the following program:

---
#include <stdio.h>

int buf[2];

static void foo(int buf1[])
{
        printf ("buf1 %08x %08x\n", buf1, &buf1);
}

int main ()
{
    unsigned int key = *(unsigned int*)&buf;
    printf ("buf  %08x %08x\n", buf, &buf);
    foo(buf);
    return 0 ;
}
---

If I compile and run it, I get the following output:

buf  00002030 00002030
buf1 00002030 bffffa00

Clearly if I naively copy and paste

    unsigned int key = *(unsigned int*)&buf;

from main to foo and just change the name, I will get the wrong result.



--Graham



_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to