【问题标题】:pass values in array without a return in C在数组中传递值而不在 C 中返回
【发布时间】:2015-11-17 19:24:23
【问题描述】:

所以我需要将三个数字和一个数组传递给一个 void 函数,该函数对数字进行排序并将其放入数组中。然后我就能够从 main 访问数组以打印出数字。

我如何让我的函数将数字放入数组并允许主要访问它而不返回任何内容?

谢谢

编辑:这是我现在的功能

void f_sort(int x, int y, int z, int *list)
{
    const int arraySize = 3;            //Constant for the size of array
    int element = 0;                    //Holds numerical value for array element
    int num1 = x;                       //Holds value of first entered number
    int num2 = y;                       //Holds value of second entered number
    int num3 = z;                       //Holds value of third entered number
    int temp;                           //Holds value of number being swapped

                                        //If the first number is larger then the second
    if (num1 > num2)
    {
        //Swap their values
        temp = num2;
        num2 = num1;
        num1 = temp;
    }

    //If the first number is larger then the third
    if (num1 > num3)
    {
        //Swap their values
        temp = num3;
        num3 = num1;
        num1 = temp;
    }

    //If the second number is larger then the third
    if (num2 > num3)
    {
        //Swap their values
        temp = num3;
        num3 = num2;
        num2 = temp;
    }

    //Add the values into the array in ascending order
    list[0] = num1;
    list[1] = num2;
    list[2] = num3;

    return;
}

int main()
{
    //Declaring an array
    int *list[3];
    //Declaring variables
    int n = 0;
    int x = 0;
    int r = 0;
    int y = 0;
    int z = 0;

printf("\n\nThe program will now take three numbers and sort them in assending order. Enter the first number: ");
    scanf("%d", &x);
    printf("Enter the second number: ");
    scanf("%d", &y);
    printf("Enter the third number: ");
    scanf("%d", &z);

    f_sort(x, y, z, *list);

    printf("The numbers in order are: %d %d %d", *list[0], *list[1], *list[2]);
}

【问题讨论】:

  • 只是在函数中给数组赋值(其实就是函数内部指向X的指针)?
  • 我没有看到您的实际问题。或者你没有看到你已经解决了它。也许你应该重新考虑你的问题。
  • 当我尝试在 main 中打印出来时,我没有打印出正确的值
  • 好,你发布了main,因为问题似乎在那里......发布minimal reproducible example!你怎么知道函数内部的值是正确的? (请注意,函数对于它的任务来说太复杂了,你应该使用swap 函数。)
  • 我马上更新我的主要内容。编译器尝试从函数中将值放入列表时会引发错误

标签: c arrays memory


【解决方案1】:

您无需返回数组即可打印其元素。只需像这样传递数组:

void f_sort(int x, int y, int z, int list[]) {
    ...
}

int main() {
    int x, y, z, list[10];
    f_sort(x, y, z, list);
    return 0;
}

【讨论】:

  • 注意:这会将指针传递给第一个元素。你不能直接在 C 中传递一个数组。这正是 OP 已经做的。
  • 我无法更改参数
  • 等等,int *list 是否意味着函数将接受变量?
【解决方案2】:
int *list[3];

创建一个指针数组,而不是你想要的ints 数组。

int list[3];

是你想要的。所以你可以消除main中的所有指针符号。

f_sort(x, y, z, list);
printf("The numbers in order are: %d %d %d", list[0], list[1], list[2]);

【讨论】:

    猜你喜欢
    • 2022-07-21
    • 2017-03-27
    • 1970-01-01
    • 2017-03-24
    • 2012-07-27
    • 2013-03-21
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    相关资源
    最近更新 更多