Casting and dereferencing of pointer
- From
- sed <sed.nivo@gmail.com>
- Date
- Aug 16, 2008, 09:33 UTC
- Message-ID
- <loom.20080816T093019-717@post.gmane.org>
Maybe I should not post in this group but anyway...
Please look at my code that do the same, except of endianness.
static void _parseItems(const unsigned char *pBuffer)
{
unsigned int itemSize;
itemSize = *((unsigned int*)pBuffer); // this give system fault
memcpy(&itemSize, pBuffer, sizeof(unsigned int)); // this works well
.......
}I'm not very experienced with C so I use git as example of good written code. In object.c I've found two functions that looks like my one.
static unsigned int hash_obj(struct object *obj, unsigned int n)
{
unsigned int hash = *(unsigned int *)obj->sha1;
return hash % n;
}static int hashtable_index(const unsigned char *sha1)
{
unsigned int i;
memcpy(&i, sha1, sizeof(unsigned int));
return (int)(i % obj_hash_size);
}I wonder why in the second used memcpy instead of: unsigned int i = *(unsigned int *)sha1 Maybe there is explanation that will help to solve my problem. Thank you