Thread: For loop behaving unexpected!!

  1. #1
    Registered User
    Join Date
    Aug 2017
    Posts
    28

    For loop behaving unexpected!!

    Here is my code to take 6 integers into an array (But taking 24 entries don't know how??):

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    void main()
    {
        int arr[6], counter, length;
        system("clear");
        
        printf("\nEnter elements of array: \n");
        
        length = sizeof(arr);
        for (counter = 0; counter < length; counter++)
        {
            printf("Array element %d : ", (counter+1));
            scanf("%d", &arr[counter]);
        }
        
        getchar();
        
    }
    Last edited by kdushyant297; 10-02-2017 at 06:19 AM.

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Sizeof(arr) counts bytes, not ints.
    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.

  4. #4
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Code:
    printf("%d\n", ( sizeof(arr)/sizeof(arr[0]) ));
    Last edited by userxbw; 10-02-2017 at 08:37 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Arrays not behaving well
    By Thunderer in forum C Programming
    Replies: 1
    Last Post: 06-25-2017, 08:36 AM
  2. Unexpected infinite loop
    By LearnerForever in forum C Programming
    Replies: 4
    Last Post: 09-23-2015, 07:31 AM
  3. File not behaving that way I want it too:
    By jocdrew21 in forum C++ Programming
    Replies: 7
    Last Post: 01-18-2014, 12:34 PM
  4. Printf... behaving Strange...
    By vsriharsha in forum C Programming
    Replies: 3
    Last Post: 04-02-2002, 02:38 AM
  5. while loop not behaving properly.
    By Dreamerv3 in forum C++ Programming
    Replies: 20
    Last Post: 01-08-2002, 05:51 PM

Tags for this Thread