On Sep 6, 2:26 pm, s0s...@gmail.com wrote:
> This code
Is broken.
> #include <stdio.h>
>
> int main(void)
> {
> int hello[] = {'h', 'e', 'l', 'l', 'o'};
> char *p = (void *) hello;
Change p to `unsigned char'. And the cast can be (void *) or (unsigned
char *).
> for (size_t i = 0; i < sizeof(hello); ++i) {
> printf("byte %2zu: <%c>", i, p[i]);
Remove the 2 in %2zu, else the output might not be meaningful.
Evaluating p[i] can invoke undefined behavior. Changing p to type
`unsigned char *' as I have suggested previously fixes this.
> if (!p[i])
> printf(" (null char)");
> printf("\n");
> }
>
> return 0;
>
> }
>
> produces this output
<snip output>
> I'm confused about the int *-to-void *-to char * conversion. The
> output shows that ints are four bytes on my machine, and the values in
> the initializer 'h', 'e', 'l', 'l', 'o' have the values 104, 101, 108,
> 108, and 111, respectively, so they're able to be represented as chars
> (duh...). But if I'd change the initializer to something like
You can convert any pointer to object to unsigned char * to inspect
its object representation.
> int hello[] = {1000, 43676, 362, 6364, 2575};
>
> I'd get this output
<snip>
> (In other words, non-printable characters.)
So what?
> Is some kind of overflow happening when I subscript the char pointer?
> Or am I simply getting meaningless values because of accessing a char
> pointer that points to something that wasn't a char object?
*ASSUMING* you change p to unsigned char *, you split the objects
representation in CHAR_BIT chunks, and you treat those bits as value
bits, even though in the original object they might be padding bits or
a sign bit.
Change your program to this for more meaningful output:
#include <stdio.h>
typedef int object_type;
#define SIZE 10
int main(void) {
object_type object[SIZE];
unsigned char *p;
size_t i;
p = (unsigned char *)object;
for(i = 0; i < sizeof object; i++)
if(isprint(p[i])) printf("p[%zu] = '%c'\n", i, p[i]);
else printf("p[%zu] = not printable\n", i);
return 0;
}