Watch this simple program, what's wrong?

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
User avatar
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Watch this simple program, what's wrong?

Post by ImLazy » Thu Jul 28, 2005 7:09 am

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)
I stay home. Don't call me out.

misof
A great helper
Posts: 430
Joined: Wed Jun 09, 2004 1:31 pm

Post by misof » Thu Jul 28, 2005 8:44 am

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.)

CDiMa
Experienced poster
Posts: 214
Joined: Fri Oct 17, 2003 5:49 pm
Location: Genova

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

Post by CDiMa » Thu Jul 28, 2005 8:49 am

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

User avatar
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Post by ImLazy » Thu Jul 28, 2005 3:27 pm

Thanks for your help. :D
I stay home. Don't call me out.

Post Reply

Return to “C++”