c - 函数指针和数组有问题

标签 c

我目前正在使用 Visual Studios 上课,不用说我很难理解指针。我创建了一个程序,但似乎不适合我。单击所需的函数类型后,我不断收到断言错误。我收到调试断言失败弹出错误。表达式:result_pointer != nullptr。它说第 1558 行

int function1(int a,int b);
int function2(int a, int b);
int function3(int a, int b);

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

int main()
{

    int num1, num2;
    int choice = 0;

    p[0] = function1;
    p[1] = function2;
    p[2] = function3;

    printf("Please enter two numbers: ");
    scanf_s("%d", &num1);
    scanf_s("%d", &num2);
    printf("Which would you like to try (1 for Math, 2 for Subtraction, 3 for Multiplication): \n");
    scanf_s("%d", choice);
    int (*i) = &choice;

    while (*i >= 0 && *i < 3) {
        (p[*i])(num1,num2);
    }

puts("Program execution compiled");
}
int function1(int a, int b) 
{
    int total;
    total = a + b;
    return total;

}
int function2(int a, int b) 
{
    int total;
    total = a - b;
    return total;
}
int function3(int a, int b) 
{
    int total;
    total = a * b;
    return total;
}

最佳答案

这就是您的代码失败的原因:

scanf_s("%d", choice);

您忘记使用运算符 & 的地址。

scanf_s("%d", &choice);

当然,您的代码还有许多其他怪癖。

例如,

  1. 为什么使用 int (*i) = &choice;?仅采用 choice 并减去 1 不是更有意义吗?无需使用指针 int i = choice - 1
  2. 您的循环将执行循环体,直到 i 小于零或大于 2,如果输入正确则永远不会出现这种情况。考虑选择另一个循环条件,或用 if 语句交换循环。
  3. 永远不要显示函数的返回值。试试这样的 printf("%d\n", (p[i])(num1,num2) (假设你已经修复了 i 是一个指针的东西)

关于c - 函数指针和数组有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33049423/

相关文章:

c - 如何使用SCons分两步编译?

c - 尝试从 C 连接到 postgres 时出现问题

c - C 中的随机排列数组

c - 为什么此代码会返回段错误?

c - 从 lcov 的覆盖率报告中排除文件

c - 将在打开时清除文件内容导致错误 C

c - 安装 msys2 并运行 "pacman -Syuu"后如何解决冲突?

c - 为什么指向结构的指针会使程序崩溃?

c - && 优先于 ||

使用 memcpy 转换字节数据