Home > Mobile >  Am I using memcpy wrong?
Am I using memcpy wrong?

Time:12-09

I'm trying to use memcpy to copy part of an unsigned int to another unsigned int within the same struct I made. But my program only prints the first printf statement and then says: Process returned -1073741819 (0xC0000005) Am I using memcpy wrong?

#include <stdio.h>
#include <string.h>

int main()
{
    struct time
    {
        unsigned int hours:5;
        unsigned int minutes:6;
        unsigned int seconds:6;
    };

    struct time t = {0x10,0b101011,45};

    printf("The time is : %d:%d:%d\n", t.hours, t.minutes, t.seconds);

    memcpy(t.minutes, t.seconds, 2);

    printf("The time is : %d:%d:%d\n", t.hours, t.minutes, t.seconds);

    return 0;
}

I've already done t.minutes = t.seconds and that copies the whole number, but I only want a portion of it.

CodePudding user response:

In response to your clarification in the comments:

When I say part of number I mean I'm trying to copy the most significant 2 bits of the unsigned int.

The way to copy individual bits is by doing bit manipulation with bitwise operators.

The two most significant bits in your 6-bit fields are therefore represented by the value 0x30 (110000 in binary). To copy these from one to another, simply clear out those bits in the destination, then mask the source and combine with bitwise-OR:

unsigned int mask = 0x30;
t.minutes = (t.minutes & ~mask) | (t.seconds & mask);

Breakdown of the above:

  • ~mask inverts the mask, meaning that bits 4 and 5 will be 0 and all other bits will be 1
  • this value is then ANDed with minutes, resulting in clearing bits 4 and 5
  • the opposite occurs when ANDing the mask with seconds, resulting in only bits 4 and 5 being preseved, and all other bits cleared
  • the two values are then combined with OR and assigned to minutes
  • Related