Antoninus Twink <> writes:
> On 17 May 2008 at 21:07, spasmous wrote:
>> I need a way to search through a block of memory for a char[2] array
>> "DA" using a pointer to a short. Ideally I would like to write
>> something like:
>>
>> short *data = ... some data...;
>> int j = 0;
>> while( data[j] != *((short*) "DA") ) j++;
>>
>> But this doesn't work.
>
> It obviously won't work if the occurence of DA in your data isn't
> aligned at a 16-bit boundary:
>
> short *x=(short *) "Hello DAMN you"; /* OK: x[3] is DA */
> short *x=(short *) "Hello, DAMN you"; /* oh dear... */
Mr. "Twink" needs to re-tune his concept of what's "obvious".
The language doesn't require that char is 8 bits, that short is 16
bits, or that short has any particular alignment requirement. For
example, on some very popular platforms, accessing a 2-byte quantity
on an odd byte address works just fine (though it's slightly slower
than accessing something on an even address).
If by "won't work" he means that the behavior is undefined, he has a
point, but one possible, and in this case very plausible, consequence
of undefined behavior is that it "works".
>> The char[2] obviously has an equivalent 16-bit value so how do I get
>> that info in a simple way?
>
> What you have, i.e. *((short*) "DA"), will do that just fine. You can
> also do something like 'D'+('A' <<
, but that relies on your machine
> being little endian...
There's no guarantee that the array associated with the string literal
"DA" is appropriately aligned for a short. It's likely to be
adequately aligned, but I wouldn't depend on it.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"