Page 1 of 1

Watch this simple program, what's wrong?

Posted: Thu Jul 28, 2005 7:09 am
by ImLazy

Code: Select all

#include <memory.h>
#include <iostream.h>
void main(){
  int a[10];
  int i;
  int value=0;

  memset(a,value,sizeof(a));

  for(i=0;i<10;i++)
    cout<<a[i]<<' ';
}
the output is 0000000000.
but when I change the code to "int value=1;", the output is 16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009.
Why??!! (I use Visual C++ 6.0)

Posted: Thu Jul 28, 2005 8:44 am
by misof
The type of the second parameter of memset is char, not int. It fills the whole memory allocated for the array with chars having the value 1. Thus, the integers stored in this memory have the value 1 + 256 + 256*256 + 256*256*256 = 16843009. (Your compiler uses 32-bit ints, as does the gcc at UVa.)

Re: Watch this simple program, what's wrong?

Posted: Thu Jul 28, 2005 8:49 am
by CDiMa
ImLazy wrote: the output is 0000000000.
but when I change the code to "int value=1;", the output is 16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009.
Why??!! (I use Visual C++ 6.0)
16843009 expressed in binary is 00000001000000010000000100000001
since you're memsetting with 1 I think it's perfectly right ;)

Ciao!!!

Claudio

Posted: Thu Jul 28, 2005 3:27 pm
by ImLazy
Thanks for your help. :D