the code logic problem

Thread Starter

TAKYMOUNIR

Joined Jun 23, 2008
352
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
Rich (BB code):
#include <stdio.h>
#include <stdlib.h>
int myfun(int *ptr);
int main()
{int *p1;
int *p2=NULL;
int  dimensions[]={80,20,35};
int   n;
p1=dimensions;
p2=&n;
n=myfun(p1);
printf("the smallest subscript is dimensions[%i]",n);
    return 0;
}
int myfun(int a[]){
    int sm=0;
    int *ptr=a;
if ((*ptr<*(ptr+1))&&(*ptr<*(ptr+2)))
sm=0;
else if (((*ptr+1)<*ptr)&&(*(ptr+1)<*(ptr+2)))
sm=1;
else
sm=2;
return sm;
}
 

WBahn

Joined Mar 31, 2012
32,868
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.

Rich (BB code):
else if (((*ptr+1)<*ptr)&&(*(ptr+1)<*(ptr+2)))
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.
 
Top