Home > Mobile >  Value assignment using calloc
Value assignment using calloc

Time:11-13

#include <stdio.h>
#include <stdlib.h>
#include <cstring>

int main()
{
    int size = 5 ;
    int* c = (int*)calloc(size,sizeof(int));
    memset(c,0,size*sizeof(int));    // when I input 1 or another value it doesn't work
    
    for (int i=0; i<size;i  ){
        printf("values %d\n", c[i]);
    }
       
    free(c);
}

This program's output in the below;

value 0
value 0
value 0
value 0
value 0

But if I change 0 value to 1:

value 16843009
value 16843009
value 16843009
value 16843009
value 16843009

I seperated the memory using calloc. I want to assign a value to this memory address that I have allocated with the memset function. When I give the value 0 here, the assignment is done successfully. I am displaying a random value instead of the values I gave outside of this value. How can I successfully perform this assignment using the memset function?

CodePudding user response:

The memset function sets each byte in the given memory segment to the given value. So you're not setting each int to 1, but each byte in each int to 1.

The decimal number 16843009 in hex is 0x01010101, which illustrates that this is exactly what happens.

If you want to set each int to a non-zero value, you'll need to do it in a loop.

CodePudding user response:

memset operates on bytes. It sets every byte to 1 rather than every 4-byte int. When you interpret the results as ints you get 0x01010101 in hex, which is 16843009 in decimal.

  • Related