#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?
The
memsetfunction sets each byte in the given memory segment to the given value. So you're not setting eachintto 1, but each byte in eachintto 1.The decimal number 16843009 in hex is 0x01010101, which illustrates that this is exactly what happens.
If you want to set each
intto a non-zero value, you'll need to do it in a loop.