【发布时间】: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函数。) -
我马上更新我的主要内容。编译器尝试从函数中将值放入列表时会引发错误