int* difference (int *a, int *b){
if (*a > *b){
*a = *a - *b;
}else{
*a = *b - *a;
}
return a;
}
int main (){
int *xp, *yp;
int x, y;
x = 9;
y = 7;
xp = &x;
yp = &y;
xp = difference (xp,yp);
printf("xp value: %d\n", *xp);
return 0;
}
For some reasons I need my program to do some mathematical operations on mono dimensional arrays. I posted a sample here because I’m concerned regarding the difference function and its returned value.
The both values are pointers but I need to do this because I can’t know for sure which of the values is grater. Is my way of doing things a good practice or is there a better way for this issue?
Personally, i try to avoid pointers as possible or, if not, always check null pointers. In this case, I would modify
difference()by:With this new way, you doesn’t need to check null values:
Besides, in main function, you doesn’t need to create pointers from int:
In resume, try to avoid pointers if not necessary or, if not, always check null values