a output question

This is a discussion on a output question within the C Programming forums, part of the General Programming Boards category; i have a very simple c program Code: int main() { int i; int four_int[4]; char* c; for (i=0; i<4; ...

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    20

    a output question

    i have a very simple c program

    Code:
    int main()
    {
    	int i;
    	int four_int[4];
    	char* c;
    	
    	for (i=0; i<4; i++)
    	four_int[i]=2;
    	
    	c = (char*)four_int;
    
    	
    	for (i=0; i<4; i++)
    	c[i]=1;
    	
    	printf("%x\n", four_int[2]);
    
    	return 0;
    }
    the output is 2, but if i change the printf statement to

    Code:
    printf("%x\n", four_int[0]);
    the output is 1010101. Can anyone tell me why this happen? Thanks!!

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,548
    Well what did you expect?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    20
    i thought it just output 1111, but i don't know why the output is 1010101 if print out four_int[0], can you explain why this happen?

  4. #4
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    one byte in hex is represented by 2 digits
    so 32-bits int will be represented by 8 digits each pair showing 1 byte...
    If each byte is set to 1 the result will be
    0x01010101

    when you truncate the leading zero you get what you get
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  5. #5
    Registered User
    Join Date
    Nov 2005
    Posts
    20
    that's make sense!!! Thanks you so much!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question: Output of data.txt from the following program
    By outlaw525 in forum C Programming
    Replies: 9
    Last Post: 06-23-2008, 03:33 PM
  2. strange virtual function output
    By George2 in forum C++ Programming
    Replies: 4
    Last Post: 02-08-2008, 07:08 AM
  3. Basic C input output program help
    By trevordunstan in forum C Programming
    Replies: 2
    Last Post: 01-27-2008, 05:41 PM
  4. a question about file output
    By wang8442 in forum C Programming
    Replies: 3
    Last Post: 12-26-2004, 02:18 AM
  5. a newbie question about file output
    By maybe in forum C Programming
    Replies: 8
    Last Post: 10-12-2004, 08:14 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21