在数组中传递值,在C中不返回
所以我需要将三个数字和一个数组传递给一个void函数,该函数对数字进行排序并将其放入数组中。然后,我可以从main访问数组以打印出数字 如何让函数将数字放入数组中,并允许主访问它而不返回任何内容 多谢各位 编辑:这是我现在的功能在数组中传递值,在C中不返回,c,arrays,memory,C,Arrays,Memory,所以我需要将三个数字和一个数组传递给一个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
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]);
}
您不需要返回数组来打印其元素。只需按如下方式传递数组:
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;
}
创建指针数组,而不是所需的整数数组
int list[3];
这就是你想要的。因此,您可以消除main中的所有指针表示法
只需将值赋给数组,数组实际上是指向函数中函数内X的指针?我看不出实际的问题。或者你看不出你已经解决了。也许你应该重新思考你的问题。当我试图在main中打印它时,我没有得到正确的打印值。你当时发布了main,因为问题似乎就在那里。。。贴一张!如何知道函数中的值是正确的?请注意,这些函数对于它的任务来说太复杂了,您应该使用swap函数。我将在稍后使用main更新。当编译器试图从functionNote中将值放入列表时抛出错误:这将向第一个元素传递指针。不能在C中直接传递数组。这正是OP所做的。我不能更改参数wait,int*list是否意味着函数将接受变量?
int list[3];
f_sort(x, y, z, list);
printf("The numbers in order are: %d %d %d", list[0], list[1], list[2]);