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?Krzysztof Duleba wrote:you just have to know what the second argument is of char type.
12081 - Reduced ID Numbers
Moderator: Board moderators
-
- Experienced poster
- Posts: 161
- Joined: Tue Oct 25, 2005 8:38 pm
- Location: buet, dhaka, bangladesh
thanks Krzysztof Duleba, but i cannot understood the line
ishtiak zaman
----------------
the world is nothing but a good program, and we are all some instances of the program
----------------
the world is nothing but a good program, and we are all some instances of the program
the syntax isayon wrote:thanks Krzysztof Duleba, but i cannot understood the linecan 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?Krzysztof Duleba wrote:you just have to know what the second argument is of char type.
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.
-
- Experienced poster
- Posts: 161
- Joined: Tue Oct 25, 2005 8:38 pm
- Location: buet, dhaka, bangladesh
at last, i understand everything
this code prints 16843009, because the 4 bytes are allocated like below:
00000001 00000001 00000001 00000001 = 16843009(decimal)
thanks to everyone
Code: Select all
#include <stdio.h>
#include <string.h>
void main()
{
int a;
memset(&a, 1, sizeof(a));
printf("%d\n", a);
}
00000001 00000001 00000001 00000001 = 16843009(decimal)
thanks to everyone
ishtiak zaman
----------------
the world is nothing but a good program, and we are all some instances of the program
----------------
the world is nothing but a good program, and we are all some instances of the program
-
- A great helper
- Posts: 481
- Joined: Sun Jun 19, 2005 1:18 am
- Location: European Union (Slovak Republic)
Very usefull is also the case if all 4 bytes of an int are -1 (11111111 binary), the value of that int is -1. Thusmisof 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.
Code: Select all
int P[100];
memset(a,-1,4*100);