c - 我如何使指针工作?

标签 c arrays function pointers printf

我有两个函数。第一个函数称为“选择器”,它将 10 个数字扫描到一个数组中,并从该数组中打印出 3 个数字。称为“计算器”的第二个函数确定应打印出 3 个数字。但是,我认为我对指针做错了什么?

void chooser() {
    int cool_array[10] = {'\0'};

    int i = 0;
    while(i < 10) {
        scanf("%d", &cool_array[i]);
        i++;
    }

    int first_num = 0;
    int second_num = 0;
    int third_num = 0;
    calculator(cool_array, first_num, second_num, third_num);

    printf("%d %d %d\n", first_num, second_num, third_num);
}

void calculator(int cool_array[],
            int *first_num, int *second_num, int *third_num) {

    int one = cool_array[0];
    int two = cool_array[1];
    int _three = cool_array[2];

    // I want the code below to change the number of first_num,
    // second_num and third_num in the chooser function, so it
    // can print the new numbers determined by the calculator function
    first_num = &one;
    second_num = &two;
    third_num = &three;
}

最佳答案

您要做的是引用 3 个变量以在“计算器”函数中更改它们 您可以将函数定义为:

void calculator(int cool_array[], int &first_num, int &second_num, int &third_num)

那么您当然不需要在计算器函数中使用取消引用运算符,只需说 first_num = one 即可更改原始变量。

关于c - 我如何使指针工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50195759/

相关文章:

c - sem_open 的意外行为

c - 递归调用中head变为0后会发生什么?

c++ - 在哪里可以获得对链表进行合并排序的 C/C++ 示例代码?

arrays - 在 Go 函数中返回局部数组的一部分安全吗?

javascript - 过滤数组并附加 li 项

function - IDL函数GAUSSFIT.pro错误

scala - 如何计算两个列表中元素出现次数的乘积?

c - 将字符分配给 char[x] 会导致段错误

java - 程序读取七个整数值并打印出每个值出现的次数

r - 有没有办法找出函数的返回类型?