I have the following simple code:
#include <bits/stdc++.h>
#define oo 0xffffff
using namespace std;
int main()
{
int v[10];
memset(v, oo, sizeof(v));
for(int i = 0; i < 10; i++)
cout << v[i] << endl;
return 0;
}
It's supposed to memset
set all values to 0xffffff, but when I print the array I get this:
$g++ -std=c++11 -o main *.cpp
$main
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
However, I have not had any problems when the values to be set are 0 or -1. For what is this?
From already thank you very much!
The fault of this behavior is
memset
, whose signature is:This function converts the value passed as the second parameter to
char
and copies it as many times as indicated by the third parameter in each of the characters of the object pointed to by the first parameter.Thus, the value
0xffffff
of type integer (int
) is converted to type character (char
). On 32-bit architectures an integer can contain 2 32 † values while a character can usually contain 2 8 ‡ values . Passing a larger type to a smaller type causes truncation so that we pass from value0xffffff
to value0xff
. The value0xff
in a signed character type ※ (char
) corresponds to-1
so copies that value to the pointer pointed to by until copies aredest
reached .count
When you copy in a loop
for
instead of usingmemset
there are no type transformations and you assign exactly the value0xffffff
(16,777,215 in typeint
) not the value0xff
(-1
in typechar
).0xffffff
(six f) is 16,777,215 and0xffffffff
(eight f) is 4,294,967,295. I was wrong to read your question, you are right, it will not appear4294967295
unless you assign0xffffffff
Another mistake of mine, very well seen :)
Old answer, not relevant . I keep it so that the comments continue to make sense.
The code is working perfectly. The value
0xffffffff
in a signed integer is-1
, to understand why I recommend reading this thread .If you change
int v[10];
to youunsigned v[10];
will get:But in C++ you shouldn't be using
memset
, usestd::copy
:Although if you wanted to fill
v
with0xffffffff
you could do it at compile time instead of run time:† Four billion, two hundred and ninety-four million, nine hundred and sixty-seven thousand, two hundred and ninety-six different values.
‡ Two hundred fifty-six different values.
※ The type
char
may or may not be signed, it is platform dependent.