I need to know when the pointer went through the whole array -> is on the first position behind it. Examplecode in c:
unsigned int ar[10];
char *pointer = (char*) ar;
while(pointer != (char*) &ar[10]){
*pointer++ = 0xff
}
Would this example work to set every element of the array to 0xffffffff?
When working with raw binary, I'd recommend to use an unsigned character type such as
uint8_t
instead ofchar
, since the latter has implementation-defined signedness.Then there are two special rules in C you can utilize:
C11 6.3.2.3/7
This allows us to inspect or modify the raw binary contents of any type in C by using a character pointer. So you can indeed set every byte of the integer array to 0xFF using a character pointer.
The other special rule is hidden inside how the additive operators work, since the [] operator is just syntactic sugar around + and dereference. C11 6.5.6/8, emphasis mine:
This allows us to check the address 1
int
beyond the end of the array.However converting between a character type pointer and an
int
pointer creates misaligned pointers and that (at least in theory) invokes undefined behavior and possibly instruction traps. So you can't just cast the character pointer to an integer pointer and compare.So the completely correct way would be to increase the character pointer by
sizeof(int)
then set 4 bytes each lap in the loop.Meaning that the following is an well-defined (but cumbersome & hard-to-read) way of setting all bytes in the array: