Page 2 of 2
Posted: Wed Nov 16, 2005 12:31 pm
by ayon
thanks Krzysztof Duleba, but i cannot understood the line
Krzysztof Duleba wrote:you just have to know what the second argument is of char type.
can you clarify in much easier way. why initializing an array with 0 is working, but not other values? can an array of structure be initialized directly with memset?
Posted: Wed Nov 16, 2005 2:53 pm
by misof
ayon wrote:thanks Krzysztof Duleba, but i cannot understood the line
Krzysztof Duleba wrote:you just have to know what the second argument is of char type.
can you clarify in much easier way. why initializing an array with 0 is working, but not other values? can an array of structure be initialized directly with memset?
the syntax is
memset( P, C, S );
where:
- P is a pointer into memory
- C is a variable of type char
- S is an integer variable (size)
memset takes the S bytes of memory starting at P and fills them with the char C.
As most of the variables use more than one byte (e.g., an int uses 4 bytes of memory), it is (in general) impossible to use memset for initialization of arrays.
There are some special cases where this
is possible. For example, if all 4 bytes of an int are zero, the value of that int is zero. Thus if you use memset with C=0 on an array of ints, it will set all the ints to zero.
Posted: Wed Nov 16, 2005 4:59 pm
by ayon
at last, i understand everything
Code: Select all
#include <stdio.h>
#include <string.h>
void main()
{
int a;
memset(&a, 1, sizeof(a));
printf("%d\n", a);
}
this code prints 16843009, because the 4 bytes are allocated like below:
00000001 00000001 00000001 00000001 = 16843009(decimal)
thanks to everyone
Posted: Sat Dec 10, 2005 12:54 pm
by Martin Macko
misof wrote:There are some special cases where this is possible. For example, if all 4 bytes of an int are zero, the value of that int is zero. Thus if you use memset with C=0 on an array of ints, it will set all the ints to zero.
Very usefull is also the case if all 4 bytes of an int are -1 (11111111 binary), the value of that int is -1. Thus
fills P with -1s.