eric eric eric eric - 2 months ago 6
C Question

I believe I am getting confused with the pointers in my program

Below I created a function that enters a while loop. In the while loop an if statement is called to traverse the list and check the numbers to see which one is the largest and which one is the smallest. When I run the program only one

printf()
is called, and prints the same
printf()
more than once. It seems to pick two numbers and print them under the same
printf()
function.I know that
firstNumber = firstNumber->next;
is supposed to traverse the list. Isn't
secondNumber = secondNumber->next->next;
supposed to point to the next number in the list?

typedef struct A_NewNumber {
struct A_NewNumber *next;
double newNum;
} NewNumber;

void NumberSize(NewNumber *start) {

NewNumber *firstNumber = start;
NewNumber *secondNumber = start;

if(start != NULL) {
while (secondNumber != NULL && secondNumber->next != NULL) {
secondNumber = secondNumber->next->next;
firstNumber = firstNumber->next;
if(secondNumber > firstNumber) {
printf("The biggest number is:%lf \n",secondNumber->newNum);
} else {
printf("The smallest number is:%lf \n",firstNumber->newNum);
}
firstNumber = firstNumber->next;
}
}
}


Example run of complete program:

Please enter a number or
'quit' to stop or 'print' to print/calculate
12
Please enter a number or
'quit' to stop or 'print' to print/calculate
13
Please enter a number or
'quit' to stop or 'print' to print/calculate
14
Please enter a number or
'quit' to stop or 'print' to print/calculate
15
Please enter a number or
'quit' to stop or 'print' to print/calculate
16
Please enter a number or
'quit' to stop or 'print' to print/calculate
17
Please enter a number or
'quit' to stop or 'print' to print/calculate
print
Numbers:12.000000
Numbers:13.000000
Numbers:14.000000
Numbers:15.000000
Numbers:16.000000
Numbers:17.000000

The biggest number is:14.000000
The biggest number is:16.000000
The smallest number is:17.000000

Answer

Can you show what the result is?

I believe that the problem is the assignment of firstNumber and secondNumber. They do seem to point to the same object. As a consequence, modifying one will modify the other. Moreover, I think it is safe to keep track of the head of the list. I would have done something like this:

void NumberSize(NewNumber *start){
   if(start==NULL){
      printf('empty list');
      return;
   }
   double high = start->newNum;
   double small= start->newNum;
   NewNumber *iterator = start->next;

   while(iterator!=NULL){
      if(iterator->newNum > high){
         high = iterator->newNum;
      }
      if(iterator->newNum < small){
         small = iterator->newNum;
      }
      iterator = iterator->next;
   }
   printf("The biggest number is:%lf \n",high);
   printf("The smallest number is:%lf \n",small);
}

I m not sure if that's what you wanted to achieve...