Pointer offset not working in memset?

Plain C, on Windows 7 and HP machines.

int main(void) {

    unsigned int a =  4294967295;
    unsigned int *b = &a;

    printf("before val: '%u'\n", *b); // expect 4294967295, got 4294967295

    memset(b+2, 0, 1);

    printf("after val: '%u'\n", *b);
    // little endian          4th      3rd     2nd       1st
    // expect 4278255615 - 11111111 00000000 11111111 11111111
    // got    4294967295 - 11111111 11111111 11111111 11111111

    return 0;

}

I want to set the third byte of an integer to 0x0, but remains unchanged. Any ideas? Thank.

On my machine, int 32 bits.

+3
source share
3 answers

Adding / subtracting a pointer does not move with just one byte - it moves by the size of the type of object being pointed to.

That is (assuming 4-byte integers)

int *p = 0x00004
int *q = p+1;
assert(q == 0x00008)

Basically, this is the same as if you were using the operator index:

int *q = &p[1]

If you want to increase the pointer by one, draw it on unsigned char *. As you did, you were rewriting memory that was not part of a variable aand might have been rewriting existing data for something else.

+7
source

b + 2 meens int .

 unsigned int *b = &a;
 memset(b+2, 0, 1);

 unsigned int *b = &a;
 memset( ((char*)b)+2, 0, 1);
+2

int , , , int ( uint32_t). ,

unsigned long a = 4294967293;
/* regular code */
a &= 0xFFFF00FF;
0

All Articles