Search code examples
carraysmemset

memset() not setting vales to one


I need to set all values of an array equal to one. I have been trying to do this using the following code:

int bulbSwitch(int n) {
    int bulbs[n];
    memset(bulbs, 1, n * sizeof(int));
    ...

However, the debugger shows that all values within the array are actually being set to 16843009. Without memset, the array values are seemingly random, positive integers. Why is this, and how would I fix it?


Solution

  • memset sets each byte of memory to the value you have specified. An int on your platform is clearly 4 bytes. So you are setting each byte of the int to be 1.

    That is, for each int, the code effectively does:

    bulbs[i] = 0x01010101;
    

    That value in decimal is exactly 16843009.

    It means you should not use memset but a simple loop instead to set each element of the array.