c puzzle #1

The expected output of the following C program is to print the elements in the array. But when actually run, it doesn't do so.
#include<stdio.h>

  #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
  int array[] = {23,34,12,17,204,99,16};

  int main()
  {
      int d;

      for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
          printf("%d\n",array[d+1]);

      return 0;
  }
Find out what's going wrong.

7 comments:

  1. Can you please explain the solution and cause of this problem..

    ReplyDelete
  2. to understand properly run gcc -E

    ReplyDelete
    Replies
    1. gcc -E test1.c

      Delete
    2. need to typecast value to signed int as below
      need to typecast as for(d=-1;d <= (int) (TOTAL_ELEMENTS-2);d++)

      Delete
  3. d is signed in intiailisation part but in codition it is unsigned
    that's the problem

    ReplyDelete
  4. Here the for loop condition begin with -1 that is wrong put d=0 then the elts will be printed...

    ReplyDelete

Your answer for the question

Related Posts Plugin for WordPress, Blogger...