C中是否允许指针的乘法和除法?

zai*_*ira 0 c pointers function-pointers 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;
Run Code Online (Sandbox Code Playgroud)

这是我的加、减、乘和除函数代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

我的代码可以运行,但是否允许?

Ard*_*der 5

C 中不允许指针的乘法和除法。

例如,

int *ptr1, *ptr2, *ptr3;

ptr3 = ptr1 * ptr2; // Error: Multiplication of pointers

ptr3 = ptr1 / ptr2; // Error: Division of pointers
Run Code Online (Sandbox Code Playgroud)

这个讨论是值得知道在 C 中的指针限制背后的原因。

进入您的代码,它起作用是因为您没有乘以或除以任何指针,而是在使用取消引用运算符时乘除这些指针所指向的值。

例如,

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
Run Code Online (Sandbox Code Playgroud)

请参阅:“引用”和“取消引用”的含义