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?
*x
is not a pointer but a value pointed byx
. and hence*x+*y;
is addition of two values pointed byx
andy
.float arr[] = {1., 2., 3., 4., 5.}, *p = arr, *p2 = arr + 2, *p3 = p / p2;
(orfloat *p3 = p2 / p;
) So what you have (on a 64-bit computer) is either(64-bit address - 2) / 64-bit address
or(64-bit address + 2) / 64-bit address
. In the first case you will have a number less than1
, in the second case, a number slightly more than1
. Both resulting addresses are likely at the bottom of the system reserved memory space (regardless you won't have valid access to the resulting address). It's just not allowed.int a = 5;
stores the immediate value5
as its value,int *b;
creates a pointer toint
, andb = &a;
stores the address ofa
asb
's value (the memory address where5
is currently stored). If you need the value stored at the memory address held by a pointer, you dereference the pointer using the unary'*'
operator, e.g.int c = *b;
.