Thread: a output question

  1. #1
    Registered User
    Join Date
    Nov 2005

    a output question

    i have a very simple c program

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

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

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    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.

  3. #3
    Registered User
    Join Date
    Nov 2005
    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
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Rishon LeZion, Israel
    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

    when you truncate the leading zero you get what you get
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

  5. #5
    Registered User
    Join Date
    Nov 2005
    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, 08:08 AM
  3. Basic C input output program help
    By trevordunstan in forum C Programming
    Replies: 2
    Last Post: 01-27-2008, 06:41 PM
  4. a question about file output
    By wang8442 in forum C Programming
    Replies: 3
    Last Post: 12-26-2004, 03: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