the code logic problem

Discussion in 'Programmer's Corner' started by TAKYMOUNIR, Nov 24, 2012.

  1. TAKYMOUNIR

    Thread Starter Active Member

    Jun 23, 2008
    351
    1
    in this program the function should return the subscript of the smallest value in the array(dimensions) like it should return dimensions[1] but when i run it it return dimension[2] so what is the wrong in my code
    Code ( (Unknown Language)):
    1. #include <stdio.h>
    2. #include <stdlib.h>
    3. int myfun(int *ptr);
    4. int main()
    5. {int *p1;
    6. int *p2=NULL;
    7. int  dimensions[]={80,20,35};
    8. int   n;
    9. p1=dimensions;
    10. p2=&n;
    11. n=myfun(p1);
    12. printf("the smallest subscript is dimensions[%i]",n);
    13.     return 0;
    14. }
    15. int myfun(int a[]){
    16.     int sm=0;
    17.     int *ptr=a;
    18. if ((*ptr<*(ptr+1))&&(*ptr<*(ptr+2)))
    19. sm=0;
    20. else if (((*ptr+1)<*ptr)&&(*(ptr+1)<*(ptr+2)))
    21. sm=1;
    22. else
    23. sm=2;
    24. return sm;
    25. }
    26.  
     
  2. WBahn

    Moderator

    Mar 31, 2012
    17,716
    4,788
    Aside from being very poorly written code from several perspectives...

    Actually, if this is nothing more than scratch code intended to quickly explore a specific concept, I don't have a problem with it.

    Now, carefully look at the following code.

    Code ( (Unknown Language)):
    1.  
    2. else if (((*ptr+1)<*ptr)&&(*(ptr+1)<*(ptr+2)))
    3.  
    Look at it not from the viewpoint of what it is supposed to do, but what it will actually do. To put it more pointedly, not what you meant to write, but what you actually wrote.
     
    TAKYMOUNIR likes this.
Loading...