2014-11-14 84 views
0

我是結構體和指針的新手。嘗試學習它們。用結構和指針做一個簡單的排序函數,但有一些問題。有人能幫我理解他們嗎?使用結構體和指針進行排序

#include<stdio.h> 
#include <stdlib.h> 

int* 
    sorting (int* arg) 
    { 

    int temp=0,j,i; 
     for(i=1;i<5;i++) 
     { 
      for(j=0;j<5-i;j++) 
      { 
       if(arg[j] >arg[j+1]) 
       { 
        temp=arg[j]; 
        arg[j]=arg[j+1]; 
        arg[j+1]=temp; 
       } 
      } 
     } 
    return arg; 
    } 

int main(){ 

    int i; 
    int n =5; 
    int *result_; 

    int *sorting_1_arg = malloc(n * sizeof *sorting_1_arg); 

    printf("Sort\n "); 
    printf("Enter 5 elements to sort: ");  

    for (i =0; i <n; i++){ 
    scanf("%d", &sorting_1_arg[i]); 
    } 

    result_4 = sorting(sorting_1_arg); 
    printf ("Sorted List recieved from Server "); 

    for (i =0; i <n; i++){ 
    printf("%d",sorting_1_arg[i]); 
    } 
    return 0; 
    } 

當我運行這段代碼:

In function 'int main()': 
[Error] invalid conversion from 'void*' to 'int*' [-fpermissive] 
+1

錯字? int * result_;' - >'int * result_4;' – BLUEPIXY 2014-11-14 17:19:42

+2

這個錯誤在C編譯器中看起來很奇怪,但是如果你將這個(C)代碼編譯爲C++的話,這將是有意義的。 – 2014-11-14 17:20:39

+0

修復錯誤@BLUEPIXY注意到,並編譯爲C,一切似乎都很好:https://ideone.com/yBWcKt – 2014-11-14 17:22:15

回答

0

的程序,似乎沒什麼問題。除了有上 線39條,未聲明的變量:

result_4 = sorting(sorting_1_arg); 

糾正它

result_ = sorting(sorting_1_arg); 

程序運行正常。只需添加一個「\ n」爲新線條,使其看起來更好。

該網站here給你一個很好的結構和指針的介紹。