Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   pecasting in c... *(long *) &array= 0x2342342;... i dont understand... (http://www.go4expert.com/forums/pecasting-c-long-array-0x2342342-i-dont-t2832/)

 max_payne 2Feb2007 22:26

pecasting in c... *(long *) &array= 0x2342342;... i dont understand...

hi everyone,

i am a noob in c.
i have problem understanding the following statement on a program:
*(long *) &array= 0x2342342;
this is supposed to fill a char array with an address in its ascii code form but can somenone please make it more clear to me?

 shabbir 3Feb2007 07:14

Re: pecasting in c... *(long *) &array= 0x2342342;... i dont understand...

Nor do I understand it. Does the program work as expected?

 DaWei 4Feb2007 00:34

Re: pecasting in c... *(long *) &array= 0x2342342;... i dont understand...

The concept is to take an array of char and treat it as a long, thus transferring 4 bytes at once. The concept is dicey, as different microprocessors arrange the 4 bytes of a long differently, depending upon their endianess. As a matter of fact, the length of a long is implementation dependent.

 max_payne 4Feb2007 02:00

Re: pecasting in c... *(long *) &array= 0x2342342;... i dont understand...

hi dawei and thanx for replying!

my prob wasnt about what this statement does althought you are 100% correct.
this statement was used so that it could fill four places of a char array (four bytes length) with a long value (four bytes length)that looks like an address in hex form...

now what i am having trouble is to understand the syntax that was used, meaning that strange typecasting...

The way i see it is:
&array[i] means-> take the address of the i element in the array
(long*) means-> cast it to a pointer for long numbers.
*(long*)..... means-> the value of the above pointer.

Is that correct???

will it be the same if i used the following set of commands?

array[0]='\x42'
array[1]='\x23'
array[2]='\x34'
array[3]='\x02'

(in reverse order because of the endian style????)

p.g.: sooo thats way big guys use debugers!!!!!!

 DaWei 4Feb2007 05:04

Re: pecasting in c... *(long *) &array= 0x2342342;... i dont understand...

The syntax is a little strange, since &array is the same as array is the same as &array[0] (array labels are treated much like pointers, since one can't treat an array as a single entity).

&array is thus the address of the char array; it's a char *.
(long *) casts it to a pointer to long, rather than a pointer to char.
* (long *) &array dereferences it for storing the 0x02342342.

However, as mentioned above, the order in which those values will be stored is implementation dependent, and it isn't necessarily just reversed. Storing them as you show (single values) might not result in what you actually want.

 All times are GMT +5.5. The time now is 02:05.