Thread: Printf... behaving Strange...

  1. #1
    Im a Capricorn vsriharsha's Avatar
    Join Date
    Feb 2002
    Posts
    192

    Question Printf... behaving Strange...

    Look at this code...

    void main()
    {
    int arr[4]={10,20,30,40};
    printf("\n%d %d %d %d\n"arr);
    }


    I understand that C prints all its arguements from right to left and when I say arr i refer to a[0] (first element) But the result i found was...
    -18 10 20 30 40

    Now, what is that -18 doing up there. If I remove a %d from the formatting list, then the last element 40 would be truncated and the result would be
    -18 10 20 30

    Can ny one explain this phenominan.

    Wishes,
    Sriharsha
    Help everyone you can

  2. #2
    Registered User
    Join Date
    Mar 2002
    Posts
    87
    Course you could do something like this

    Code:
    void main(){
      int arr[4] = {10,20,30,40};
      for(int i=0;i<sizeof(arr);i++){
        printf("%d\n",arr[i]);
      }
    }
    PuterPaul.co.uk - Portfolio site

  3. #3
    Im a Capricorn vsriharsha's Avatar
    Join Date
    Feb 2002
    Posts
    192

    Talking

    Well,
    I am aware of that method of printing out an array but my question was, "why was printf behaving so strangly". I wanted an explanation for the output of that particular code. Anyway thanks for ur time.

    Regards,
    Sriharsha.
    Help everyone you can

  4. #4
    Registered User
    Join Date
    Mar 2002
    Posts
    10
    HI Sriharsha

    actually your program is catching the last two character of the address of the array i.e __18.
    as in this statement

    printf("\n%d %d %d %d\n",arr);

    you are calling arr which is actually address of the array.
    that's why it is first printing the address first and then its elements.

    for printing the element of the array
    pdstatha's idea is best.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. IF CONDITION plese help
    By birumut in forum C Programming
    Replies: 12
    Last Post: 03-06-2009, 09:48 PM
  2. making it portable.....?
    By ShadeS_07 in forum C Programming
    Replies: 11
    Last Post: 12-24-2008, 09:38 AM
  3. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  4. Simple C question: user input to repeat a loop
    By evernaut in forum C Programming
    Replies: 2
    Last Post: 11-18-2006, 09:23 AM
  5. Drawing tables in C
    By stanoman in forum C Programming
    Replies: 5
    Last Post: 10-09-2003, 10:14 AM