2015-11-17 27 views
-2

所以我需要將三個數字和一個數組傳遞給一個void函數,該函數將數字排序並將其放入數組中。然後我可以從main訪問數組來打印出數字。在數組中傳遞值而不返回C

如何讓我的函數將數字放入數組中,並允許對其進行主訪問而不返回任何內容?

謝謝

編輯:這裏是我的功能,截至目前

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]); 
} 
+0

只需將值賦給函數中的數組(實際上是指向函數內的X的指針)? –

+0

我沒有看到你的實際問題。或者你沒有看到你已經解決了它。也許你應該重新思考你的問題。 – Olaf

+0

當我嘗試在main中打印出來時,我沒有得到正確的打印值 –

回答

0

您不需要返回數組打印它的元素。簡單地傳遞數組是這樣的:

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; 
} 
+0

中將值放入列表時引發錯誤。注意:這會將指針傳遞給第一個元素。你不能直接在C中傳遞數組。這正是OP已經做的。 – Olaf

+0

我無法更改參數 –

+0

等待,'int * list'是否意味着該函數將接受一個變量? – Cesare

0
int *list[3]; 

創建指針數組,而不是你想要int在數組。

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]);