Chef Flambe
Chef Flambe

Reputation: 885

pointers and memory addresses

I recently did an assignment using bit masking and shifting to manipulate a 4 byte int.

I got to wondering if it was possible to set a char pointer to the start of the int variable and then step through the int as if it was a 1 byte char by using the char pointer.

Is there a way to do this or something similar? I tried to set the char pointer to an int but when I step ahead by 1 it jumps 4 bytes instead.

Just trying to think of alternative ways of doing the same thing.

Upvotes: 2

Views: 135

Answers (3)

Jack
Jack

Reputation: 133557

Of course you can, this code shows the behavior:

#include <stdio.h>

int main()
{
  int value = 1234567;
  char *pt = (char*) &value;

  printf("first char: %p, second char: %p\n", pt, pt+1);
}

This outputs:

first char: 0x7fff5fbff448, second char: 0x7fff5fbff449

As you can see difference is just 1 byte as intended, this because arithmetic on pointers has been done after casting the type to a smaller kind of data.

Upvotes: 3

mfsiega
mfsiega

Reputation: 2872

I imagine this should do what you want:

int x = 42;
char *c = (char *) &x;
char byte0 = c[0];
char byte1 = c[1];
char byte2 = c[2];
char byte3 = c[3];

Upvotes: 2

Martin Beckett
Martin Beckett

Reputation: 96119

Yes a char pointer would step by 1byte at a time, you probably inadvertently cast it to an int.

Another complexity is the order of the bytes in an int, at least on Intel

Upvotes: 1

Related Questions