ranjan kumar ojha <[EMAIL PROTECTED]> wrote:
>
> Hi friends,
>
> I got perplexed because of memset.
Why?
> look
No. Do not try to learn C or C++ by experimentation!!
Get yourself a good reference and read it.
> int a[100];
> memset(a,0,sizeof(a));
> then it is filling 0 in array.
>
> int a[100];
> memset(a,-1,sizeof(a));
> then it is filling -1 in array.
No it isn't. It's filling UCHAR_MAX into each byte of the
array. The wider result is that each integer has an all
bits 1 representation. On your machine, and most others,
that representation is the int value -1.
> but
> int a[100];
> memset(a,1,sizeof(a));
> then it is filling array by a big number.
No it isn't. It's putting a 1 in each byte of the array.
> can any one explain this abnormal behaviour of memset?
Your failure to RTFM does not mean the behaviour is abnormal.
> plz also tell me internal implementation of memset.
No! You are _much_ better served by understanding _what_ memset
does, as opposed to _how_ it does it. Besides, different
implementations will implement it in different ways.
7.21.6.1 The memset function
Synopsis
1 #include <string.h>
void *memset(void *s, int c, size_t n);
Description
2 The memset function copies the value of c (converted to
an unsigned char) into each of the first n characters of
the object pointed to by s.
Returns
3 The memset function returns the value of s.
In other words, it is functionally equivalent to...
void *memset(void *s, int c, size_t n)
{
unsigned char *us = s;
unsigned char uc = c;
while (n--) *us++ = uc;
return s;
}
> if we fill 0 in an array using for loop & using memse
> also, which one will be faster or both will take same time.
Learn to stop the engine exploding before you try to learn
how to make it go faster. ;-)
You can use memset to set integers to zero, but you can't
use it to set floating point objects to 0.0, nor can you
set pointer objects to null pointers.
So the memset function is rarely used. It's use in setting
memory to non-zero values is even rarer and is typically
only applied to character (byte) arrays.
--
Peter