2010-01-26 20 views
1

的陣列交換元件說我有這個結構:在結構

struct MyStruct { 
    int iID; 
    int iMyNumber; 
}; 

然後我定義MyStructs的數組:

struct MyStruct msTest[3]; 

我上的結構類似於在做排序操作這個通過查看ID。現在,只要我找出哪些記錄應該交換排序數組,我必須做實際的交換。我嘗試這樣做:

if (iSmallest != iCntr) { 
    stPTmp = &stXDB[iCntr]; 
    &stXDB[iCntr] = &stXDB[iSmallest]; 
    &stXDB[iSmallest] = &stPTmp; 
} 

stPTmp被定義爲void *stPTmp;iCntriSmallest包含的記錄的索引來進行交換。我的代碼不起作用,但我該如何解決它?

回答

4

需要交換的元素,不是指針,

struct MyStruct stTmp; 

if (iSmallest != iCntr) { 
    stTmp = stXDB[iCntr]; 
    stXDB[iCntr] = stXDB[iSmallest]; 
    stXDB[iSmallest] = stTmp; 
} 

不是非常有效的,但你的結構是小,所以它只有一點點比交換指針更昂貴。

3

你可以只讓別人想一想,即使用qsort()

#include <stdlib.h> 


int compare_struct(const void *a, const void *b) 
{ 
    const struct MyStruct *sa = a, *sb = b; 

    return (sa->iID < sb->iID) ? -1 : sa->iId > sb->iId; 
} 

qsort(msTest, sizeof msTest/sizeof *msTest, sizeof *msTest, compare_struct); 

注意,這完全去除需要寫的交換功能。在引擎蓋下,這可能會更昂貴一些(可以使用malloc(),幾乎可以肯定使用memcpy()),但是寫起來更容易,維護也更容易。

3

約翰已經回答了你的問題,但你struct有幾分,你可以使用標準庫qsort()功能:

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

struct MyStruct { 
    int iID; 
    int iMyNumber; 
}; 

/* comparison function, should return < 0, > 0 or == 0 
    if a < b, a > b or a == b respectively. Used by qsort */ 
static int comp_mystruct(const void *a, const void *b); 

/* utility function to print an array of our struct */ 
static void print_mystruct(const void *start, size_t n); 

int main(void) 
{ 
    /* some data */ 
    struct MyStruct data[] = { 
     { 1, 10 }, 
     { 5, 50 }, 
     { 2, 20 }, 
     { -3, 100 } 
    }; 
    size_t ndata = sizeof data/sizeof data[0]; 

    /* before sorting */ 
    print_mystruct(data, ndata); 
    putchar('\n'); 

    /* sort the array now */ 
    qsort(data, ndata, sizeof data[0], comp_mystruct); 

    /* after sorting */ 
    print_mystruct(data, ndata); 

    return 0; 
} 

static void print_mystruct(const void *start, size_t n) 
{ 
    size_t i; 
    const struct MyStruct *s = start; 
    for (i=0; i < n; ++i) { 
     printf("% 3d % 3d\n", s[i].iID, s[i].iMyNumber); 
    } 
} 

static int comp_mystruct(const void *a, const void *b) 
{ 
    const struct MyStruct *sa = a; 
    const struct MyStruct *sb = b; 
    if (sa->iID > sb->iID) { 
     return 1; 
    } else if (sa->iID < sb->iID) { 
     return -1; 
    } else { 
     return 0; 
    } 
} 

程序的輸出是:

1 10 
    5 50 
    2 20 
-3 100 

-3 100 
    1 10 
    2 20 
    5 50 

優勢是qsort()是標準的,你可以用它來排序。