Withing a function is there any legal way to interpret a char *
parameter, of a given length, as an pointer of a different integral type, and then access said converted pointer? There seem to be plenty of illegal (UB) ways to do it...
For example given the following function prototype:
int32_t sum_32(char *a, int len);
I'd like to know if there is a way of writing something functionally equivalent to the following code, legally:
int32_t sum_32(char *a, int len) {
assert(len % 4 == 0);
int32_t total = 0;
for (int i = 0; i < len / 4; i++) {
total += ((int32_t *)a)[i];
}
return total;
}
Of course, one way of doing it just to break down the accesses into character-sized access with shifting to recombine into a larger value (with some assumption about the endianness, here assuming LE):
int32_t sum_32(char *a, int len) {
assert(len % 4 == 0);
int32_t total = 0;
for (int i = 0; i < len; i += 4) {
int32_t val = (int32_t)
(a[i+0] << 0) +
(a[i+1] << 8) +
(a[i+2] << 16) +
(a[i+3] << 24) ;
total += val;
}
return total;
}
... but here I am looking for solutions that access the underlying array one int32_t
at a time.
If the answer is "it's not possible", does the answer change if I know the source of the char *a
is an allocation function - or, more broadly, are there any additional restrictions I can put on a
such that accessing it as a larger type is legal?