2011-08-17 151 views
1

所以下面的代碼編譯時沒有gcc的警告等,但由於某種原因,交換代碼實際上並沒有通過交換值來修改數組......這裏可能會發生什麼?一個有趣的事情是,temp總是包含我想要的,它只是不被使用。C - 結構數組元素交換

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

//STRUCTURES 
struct complex_ 
{ 
    double re, im; 
}; 

typedef struct complex_ complex; 

//PROTOTYPES 
int reverseBits(int x,int elements); 
complex new_complex(double re, double im); 

//MAIN 
int main() 
{ 
    int n,m,elements = 8; 
    complex temp,**v; 

    //Allocate memory for the struct array... 
    v = malloc(sizeof(complex*)); 
    *v = malloc(sizeof(complex)*elements); 

    //Initialize the struct array... 
    for (n = 0; n < elements; n++) 
    { 
     (*v)[n] = new_complex(n,0); 
    } 

    //View the initialized struct array contents... 
    for (n = 0; n < elements; n++){printf("%f+%fi\n", (*v)[n].re,(*v)[n].im);} 

    //Swap elements for the bit reversal... 
    for (n = 0; n < elements; n++) 
    { 
     m = reverseBits(n,elements); 
     temp = (*v)[n]; 
     (*v)[n] = (*v)[m]; 
     (*v)[m] = temp; 
    } 

    //View the new swapped struct array contents... 
    for (n = 0; n < elements; n++){printf("%f+%fi\n", (*v)[n].re,(*v)[n].im);} 

    return 0; 
} 

//FUNCTION DEFINITIONS 
int reverseBits(int x,int elements) 
{ 
    //This function performs a binary bit reversal 
    //for example 3 = 011 => 110 = 6... 
    int num_bits = log2(elements); 
    int reverse_x = 0; 
    int i; 

    for (i = 0; i < num_bits; i++) 
    { 
     if((x & (1 << i))) 
      reverse_x |= 1 << ((num_bits - 1) - i); 
    } 
    return reverse_x; 
} 

complex new_complex(double re, double im) 
{ 
    //This function creates a new complex number. 
    complex r; 
    r.re = re; 
    r.im = im; 
    return r; 
} 
+2

您沒有執行分配權限。你現在先分配一個指向'complex *'的指針,然後分配一個第一個指針指向的'complex'數組。你最好分配一個'complex *'指針數組,'malloc(sizeof(complex *)* elements)',並用'new_complex'填充它。另外,你應該釋放所有分配的內存 - 首先是複合體,然後是數組。 – eran

+0

我創建一個指向數組的指針的原因是我將在其他函數中修改該數組。這仍然是一個問題嗎?另外,我同意 - 我應該釋放內存。 –

+0

你仍然可以按照我建議你創建它的方式傳遞數組。如果你想要其他函數來創建數組或者用另一個函數替換它,你可以通過'&v'來實現,並且在那裏執行'* v = some_other_complex_star_star'。但是如果你想改變數組的內容,你可以按原樣傳遞 - 'v'。 – eran

回答

3

如果您將數組的所有項目與「反轉」索引處的項目交換一次,那麼您將以再次開始狀態結束。 。即,對於8的陣列大小,這些互換完成:

  • 交換項索引0處關於項目索引0處
  • 交換項索引1處關於項目在索引4 的(a)
  • 在索引6 在索引處關於項目索引圖4(b)
  • 交換項目1 的(a)
  • 0索引2與項目
  • 交換項索引2
  • 交換項在索引3項在索引4 (b)中在索引處關於項目索引7
  • 交換項目7

通知在與項目索引

  • 交換項中的索引5
  • 交換項在索引6項標有相同字母的交換((a)(b))彼此抵消,其他交易爲空操作。

  • +0

    這很有道理。那麼實現期望的價值互換的正確方法是什麼? –

    +0

    @nick_name:什麼是期望值交換? –