Reputation: 29
I remember my programming prof said that multiplication and division of pointers are not allowed. We have a seatwork that needs us to create a program that adds, subtracts, multiplies and divides two numbers using pointers.
This is my code in the main function:
float num1, num2, a, b, c, d;
printf("Enter a number: ");
scanf("%f", &num1);
printf("Enter another number: ");
scanf("%f", &num2);
a = add(&num1, &num2);
b = subtract(&num1, &num2);
c = multiply(&num1, &num2);
d = divide(&num1, &num2);
printf("Sum: %.2f\nDifference: %.2f\nProduct: %.2f\nQuotient: %.2f", a, b, c, d);
getch();
return 0;
This is my code for the add, subtract, multiply, and divide functions:
float add(float *x, float *y)
{
return *x+*y;
}
float subtract(float *x, float *y)
{
return *x-*y;
}
float multiply(float *x, float *y)
{
return *x * *y;
}
float divide(float *x, float *y)
{
return *x / *y;
}
My code runs and works but is it allowed?
Upvotes: 2
Views: 14105
Reputation: 3995
Multiplication and division of pointers are not allowed in C.
For example,
int *ptr1, *ptr2, *ptr3;
ptr3 = ptr1 * ptr2; // Error: Multiplication of pointers
ptr3 = ptr1 / ptr2; // Error: Division of pointers
This discussion is worthwhile to know the reasons behind this restriction on pointers in C.
Getting into your code, it works because you are not multiplying or dividing any pointers but multiplying and dividing the values pointed by those pointers as you have used the dereference operator.
For example,
int a = 1, b = 2, c = 3;
int *ptr1 = &a;
int *ptr2 = &b;
int *ptr3 = &c;
*ptr3 = *ptr1 * *ptr2; // No error: c = a * b
*ptr3 = *ptr1 / *ptr2; // No error: c = a / b
See: meaning of "referencing" and "dereferencing"
Upvotes: 7
Reputation: 120
*x and *y refer to the values pointed by them, not the pointers.
*x * *y -> allowed.
x * y -> not allowed.
Upvotes: 4