3

I have written a small program to get used to memset() operation:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> int main() { int arr[10], i; int t = INT_MAX; memset(arr, t, sizeof(arr)); for (i = 0; i < 10; i++) printf("%d\t",arr[i]); printf("%d",t); return 0; } 

The result of the above program is:

-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 2147483647 

What is the behaviour of the memset() in the above program? Why is it setting the array elements to -1?

2 Answers 2

10

memset only takes the lower eight bits of the value and fills the whole buffer with these bits. The lower eight bits of MAX_INT are all ones (0xFF), and thus the array is afterwards filled with all ones. For signed integers, this is -1.

Sign up to request clarification or add additional context in comments.

3 Comments

Assuming int is 32 bits, a 4 byte, you mean, memset only uses bits 0 to 7 to determine the value, which they represent and put this value into target memory location? If yes, this means also, as unsigned char could only handle old fashioned ascii?
I'm not sure I understand the question. bits 0 to 7 are eight bits, which is one bit more than ascii (if you don't take parity into account). But yes, if you want a pattern larger than 8 bits, you need to use a different function (wmemset comes to mind) or a for loop.
All right. You understood well and answered my question. Thx.
0

Memset sets the first sizeof(arr) bytes of the block of memory pointed by arr to t interpreted as an unsigned char. So what u get when you read out ints from arr depends in the interpretation of those bytes on your platform.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.