ComplicatedPhenomenon ComplicatedPhenomenon - 1 year ago 35
C Question

basic problems in scanf format and using function pointer

I am trying to understand function pointers. then I was give an example, I typed these code by self

#include <stdio.h>

int sum(int a, int b);
int subtract(int a, int b);
int mul(int a, int b);
int div(int a, int b);

int (*p[4]) (int x, int y);

int main(void)
{
int result;
int i, j, op;

p[0] = sum; /* address of sum() */
p[1] = subtract; /* address of subtract() */
p[2] = mul; /* address of mul() */
p[3] = div; /* address of div() */

printf("Enter two numbers: ");
scanf("%d %d ", &i, &j);

printf("0: Add, 1: Subtract, 2: Multiply, 3: Divide\n");
do {
printf("Enter number of operation: ");
scanf("%d", &op);
} while(op<0 || op>3);

result = (*p[op]) (i, j);
printf("%d", result);

return 0;
}

int sum(int a, int b)
{
return a + b;
}

int subtract(int a, int b)
{
return a - b;
}

int mul(int a, int b)
{
return a * b;
}

int div(int a, int b)
{
if(b)
return a / b;
else
return 0;
}


then I compiled and executed it, something weird happened. after typing into two numbers. then in principle should followed statement
printf("0: Add, 1: Subtract, 2: Multiply, 3: Divide\n");
, but what happened was it was still waiting for me to input number of operation. then that statement
printf("0: Add, 1: Subtract, 2: Multiply, 3: Divide\n");
appeared.

I checked the code for a long time. The I found out the inconspicuous problem that I typed
scanf("%d %d \n", &i, &j);
instead of
scanf("%d %d", &i, &j);


It's very likely to be a silly question, but I still need explanation, why the order changed because of that mistake? Also I wonder why input those 2 two numbers in this way
scanf("%d %d ", &i, &j);
instead of
scanf("%d %d ", i, j);
?

Answer Source

scanf is a nasty beast. The difference between using scanf("%d %d ", &i, &j); and scanf("%d %d", &i, &j); is the extra whitespace at the end of the former statement. This makes scanf want to skip more whitespace; but because there isn't any, it asks the console to get more (prompting you for input). Once you press ENTER, it takes that as a newline and gobbles that up - then scanf lets you continue.

Also I wonder why input those 2 two numbers in this way scanf("%d %d ", &i, &j); instead of scanf("%d %d ", i, j);?

This is because scanf needs to modify the integers you are passing to it. In C, if you want to modify your argument then you need to get passed the pointer to the value. If the value itself is parsed and taken as a pointer, then you'd most likely get a segmentation fault.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download